Client side validation
21 Feb 20243 minutes to read
To achieve the client side validation in a DatePicker control by using Essential JavaScript 2 FormValidator. It provides an option to customize the feedback error messages to the corresponding fields to take action to resolve the issue.
In this below example, the required field validation is implemented by mapping the name attribute value to the rules property. It will validate the DatePicker control and display the validation message when the textbox value is empty during form post back or focus out.
<form id="form-element" class="form-vertical">
<div class="form-group">
<div class="col-sm-6">
@Html.EJS().DatePicker("datevalue").Value(ViewBag.value).Render()
</div>
</div>
</form>
<script>
document.addEventListener('DOMContentLoaded', function () {
var options = {
rules: {
//must specify the name attribute value in rules section
'datevalue': { required: true }
},
customPlacement: (inputElement, errorElement) => {
//to place the error message in custom position
//inputElement - target element where the error text will be appended
//errorElement - error text which will be displayed.
inputElement.parentElement.parentElement.appendChild(errorElement);
}
};
var formObject = new ej.inputs.FormValidator('#form-element', options);
});
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EJ2CoreSampleBrowser.Controllers
{
public class HomeController: Controller
{
public ActionResult sample()
{
ViewBag.value = new DateTime(DateTime.Now.Year,DateTime.Now.Month,14);
return View();
}
}
}