Client side validation using FormValidator

28 Feb 20223 minutes to read

To achieve client side validation in a TimePicker component, use Essential JavaScript 2 FormValidator. It provides an option to customize feedback error messages to the corresponding fields for taking action and resolving the issue.

In the following example, the required field validation is implemented by mapping the name attribute value to the rules property. It validates the TimePicker component and displays 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-3 control-label">Required</div>
        <div class="col-sm-6">
            @Html.EJS().TimePicker("formTest").Value(ViewBag.value).Render()
        </div>
    </div>
</form>

<script>

    document.addEventListener('DOMContentLoaded', function () {
        var options = {
            rules: {
                //must specify the name attribute value in rules section
                'formTest': { 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 DefaultFunctionalities()
        {
            ViewBag.value = DateTime.Now;
            return View();
        }
    }
}