Client side validation in EJ2 TypeScript Datepicker control

26 Apr 20233 minutes to read

To achieve the client side validation in a DatePicker component 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 component and display the validation message when the textbox value is empty during form post back or focus out.

import { DatePicker } from '@syncfusion/ej2-calendars';
import { FormValidator, FormValidatorModel } from '@syncfusion/ej2-inputs';
// creates datepicker with readonly.
let datepickerObject: DatePicker = new DatePicker({
    // sets the palceholder property.
    placeholder: 'Enter date',
    // sets the value
    value: new Date()
});
datepickerObject.appendTo('#element');

let options: FormValidatorModel = {
    rules: {
        'datevalue': { required: true }
    },
    customPlacement: function (inputElement, errorElement) {
        //to place the error message in custom position.
        (<HTMLElement>inputElement).parentElement.parentElement.appendChild(errorElement);
    }
}
let formObject: FormValidator = new FormValidator('#form-element', options);
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Essential JS 2 DatePicker control</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript UI Controls" />
    <meta name="author" content="Syncfusion" />
    <link href="styles.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-buttons/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-inputs/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-popups/styles/material.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/28.1.33/ej2-calendars/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    <div id='loader'>LOADING....</div>
    <div id='container'>
        <form id="form-element" class="form-vertical">
            <div class="form-group">
                <div class="col-sm-6">
                    <input type="text" id="element" name="datevalue" class="form-control" />
                </div>
            </div>
        </form>
    </div>
</body>

</html>