Validation rules in EJ2 JavaScript Form validator control

2 Feb 202424 minutes to read

Default Rules

The FormValidator has following default validation rules, which are used to validate the form.

Rules Description Example
required The form input element must have any input values a or 1 or -
email The form input element must have valid email format values <form@syncfusion.com>
url The form input element must have valid url format values http://syncfusion.com/
date The form input element must have valid date format values 05/15/2017
dateIso The form input element must have valid dateISO format values 2017-05-15
number The form input element must have valid number format values 1.0 or 1
digits The form input element must have valid digits values 1
maxLength Input value must have less than or equal to maxLength character length if maxLength: 5, check is valid and checking is invalid
minLength Input value must have greater than or equal to minLength character length if minLength: 5, testing is valid and test is invalid
rangeLength Input value must have value between rangeLength character length if rangeLength: [4,5], test is valid and key is invalid
range Input value must have value between range number if range: [4,5], 4 is valid and 6 is invalid
max Input value must have less than or equal to max number if max: 3, 3 is valid and 4 is invalid
min Input value must have greater than or equal to min number if min: 4, 5 is valid and 2 is invalid
regex Input value must have valid regex format if regex: '^[A-z]+$', a is valid and 1 is invalid

The rules option should map the input element’s name attribute.
The FormValidator library only validates the mapped input elements.

Defining Custom Rules

You can also define custom rules in the rules property and validate the form with custom logics.

The custom validation method need to return the boolean value for validating an input.

var customFn = (args) => {
    return args['value'].length >= 5;
};
var options = {
    rules: {
        'user': { required: true },
        'password': { minLength: [customFn, 'Need atleast 5 letters'] }
    }
};
var formObject = new ej.inputs.FormValidator('#form-element', options);
<!DOCTYPE html><html lang="en"><head>
    <title>EJ2 Form Validator</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="index.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-base/styles/material.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    
    
<script src="https://cdn.syncfusion.com/ej2/27.2.2/dist/ej2.min.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    
    <div id="container">
        <form id="form-element" class="form-horizontal">
            <div class="form-group">
                <label class="col-sm-3 control-label" for="user">User Name</label>
                <div class="col-sm-6">
                    <input type="text" id="required" name="user" class="form-control">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label" for="password">Password</label>
                <div class="col-sm-6">
                    <input type="password" id="number" name="password" class="form-control">
                </div>
            </div>
        </form>
    </div>


<script>
var ele = document.getElementById('container');
if(ele) {
  ele.style.visibility = "visible";
}   
      </script>
<script src="index.js" type="text/javascript"></script>
</body></html>
#container {
    visibility: hidden;
    padding: 10px;
}

#loader {
    color: #008cff;
    height: 40px;
    width: 30%;
    position: absolute;
    top: 45%;
    left: 45%;
}

Adding or Removing Rules

After creating FormValidator object, you can add more rules to an input element by using addRules
method and you can also remove an existing rule from the input element by using removeRules method.

import {FormValidator, FormValidatorModel} from '@syncfusion/ej2-inputs';

let options: FormValidatorModel = {
    rules: {
        'user': { required: true },
        'age': { number: true }
    }
}
let formObject: FormValidator = new FormValidator('#form-element', options);
// Add email rule to user element
formObject.addRules('user', { maxLength: 7 });
// Remove number rule from age element
formObject.removeRules('age', ['number']);

Validating a Form

You can manually trigger validation by calling the validate method of FormValidator.

var options = {
    rules: {
        'product_name': { required: true },
        'rating': { range: [1, 5] }
    }
};
var formObject = new ej.inputs.FormValidator('#form-element', options);
// validate all input elements in the form
formObject.validate();
<!DOCTYPE html><html lang="en"><head>
    <title>EJ2 Form Validator</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="index.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-base/styles/material.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    
    
<script src="https://cdn.syncfusion.com/ej2/27.2.2/dist/ej2.min.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    
    <div id="container">
        <form id="form-element" class="form-horizontal">
            <div class="form-group">
                <label class="col-sm-3 control-label" for="product_name">Product Name</label>
                <div class="col-sm-6">
                    <input type="text" id="required" name="product_name" class="form-control">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label" for="rating">Rating</label>
                <div class="col-sm-6">
                    <input type="text" id="number" name="rating" class="form-control">
                </div>
            </div>
        </form>
    </div>


<script>
var ele = document.getElementById('container');
if(ele) {
  ele.style.visibility = "visible";
}   
      </script>
<script src="index.js" type="text/javascript"></script>
</body></html>
#container {
    visibility: hidden;
    padding: 10px;
}

#loader {
    color: #008cff;
    height: 40px;
    width: 30%;
    position: absolute;
    top: 45%;
    left: 45%;
}

Validating a Single Element

The validate method have an optional argument, where you can pass an input element’s name attribute to validate its value against the defined rule.

import {FormValidator, FormValidatorModel} from '@syncfusion/ej2-inputs';

let options: FormValidatorModel = {
    rules: {
        'user': { required: true },
        'age': { number: true }
    }
}
let formObject: FormValidator = new FormValidator('#form-element', options);
// validate user element alone
formObject.validate('user');

HTML5 Form Validation

HTML5 validation is the ability to validate the user data without relying any scripts. This is done by using validation attributes on form elements, which allows you to specify rules for a form input like whether a value needs to be filled In the maximum and minimum length of the data, whether it needs to be number, an email address, or something else and pattern that it match. If the entered data follows all the
specified rules, it is considered as valid; if not, it is considered as invalid.

// Initialize the Submit Button.
    var buttonFormValidate = new ej.buttons.Button({
        isPrimary: true
    });
    buttonFormValidate.appendTo('#validateSubmit');
    // Initialize the Reset Button.
    var buttonReset = new ej.buttons.Button();
    buttonReset.appendTo('#resetbtn');
    var options = {
        // Initialize the CustomPlacement.
        customPlacement: function (inputElement, errorElement) {
            inputElement.parentElement.appendChild(errorElement);
        }
    };

    // Initialize the FormValidator.
    var formObj = new ej.inputs.FormValidator('#formId', options);
    document.getElementById('formId').addEventListener("submit", function (e) {
        e.preventDefault();
        if (formObj.validate()) {
            alert('Your form has been submitted.');
            formObj.reset();
        }
    });
<!DOCTYPE html><html lang="en"><head>
    <title>EJ2 Form Validator</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="index.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-base/styles/material.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-inputs/styles/material.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-buttons/styles/material.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    
    
<script src="https://cdn.syncfusion.com/ej2/27.2.2/dist/ej2.min.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>

<body>
    
    <div id="container">
        <div class="content-wrapper" style="margin-bottom: 25px">
            <div class="form-title"><span>HTML5 Validation</span></div>
            <form id="formId" class="form-horizontal">
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="required" name="Required" data-required-message="Required field" required="" data-msg-containerid="requiredError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="required">Required</label>
                    </div>
                    <div id="requiredError"></div>
                </div>
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="email" name="Email" data-validation="email" data-email-message="Please enter valid email address." data-required-message="Required field" required="" data-msg-containerid="emailError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="email">Email</label>
                    </div>
                    <div id="emailError"></div>
                </div>
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="url" name="Url" data-validation="url" data-url-message="Please enter valid url." data-required-message="Required field" required="" data-msg-containerid="urlError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="url">URL</label>
                    </div>
                    <div id="urlError"></div>
                </div>
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="date" name="Date" data-validation="date" data-date-message="Please enter valid date." data-required-message="Required field" required="" data-msg-containerid="dateError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="date">Date</label>
                    </div>
                    <div id="dateError"></div>
                </div>
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="dateIso" name="DateISO" dateiso="true" data-dateiso-message="Please enter valid dateISO format(YYYY-MM-DD)." data-required-message="Required field" required="" data-msg-containerid="dateisoError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="dateIso">Date ISO (YYYY-MM-DD)</label>
                    </div>
                    <div id="dateisoError"></div>
                </div>
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="number" name="Number" data-validation="number" data-number-message="Please enter Integer or Decimal only." data-required-message="Required field" required="" data-msg-containerid="numberError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="number">Integer or Decimal</label>
                    </div>
                    <div id="numberError"></div>
                </div>
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="digits" name="Digits" digits="true" data-digits-message="Please enter digits only." data-required-message="Required field" required="" data-msg-containerid="digitError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="digits">Positive Integer</label>
                    </div>
                    <div id="digitError"></div>
                </div>
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="maxlen" name="MaxLength" maxlength="5" data-maxlength-message="Please enter no more than 5 characters." data-required-message="Required field" required="" data-msg-containerid="maxlenError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="maxlen">Maximum 5 characters</label>
                    </div>
                    <div id="maxlenError"></div>
                </div>
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="minlen" name="MinLength" minlength="5" data-minlength-message="Please enter at least 5 characters." data-required-message="Required field" required="" data-msg-containerid="minlenError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="minlen">Minimum 5 characters</label>
                    </div>
                    <div id="minlenError"></div>
                </div>
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="rangelen" name="RangeLength" rangelength="[5, 10]" data-rangelength-message="Please enter a value between 5 and 10 characters long." data-required-message="Required field" required="" data-msg-containerid="ranlenError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="rangelen">Characters length between 5 to 10</label>
                    </div>
                    <div id="ranlenError"></div>
                </div>
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="range" name="Range" range="[5, 10]" data-range-message="Please enter a value between 5 and 10." data-required-message="Required field" required="" data-msg-containerid="ranError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="range">Value between 5 to 10</label>
                    </div>
                    <div id="ranError"></div>
                </div>
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="max" name="Max" max="5" data-max-message="Please enter a value less than or equal to 5." data-required-message="Required field" required="" data-msg-containerid="maxError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="max">Max (maximum value 5)</label>
                    </div>
                    <div id="maxError"></div>
                </div>
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="min" name="Min" min="5" data-min-message="Please enter a value greater than or equal to 5." data-required-message="Required field" required="" data-msg-containerid="minError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="min">Min (minimum value 5)</label>
                    </div>
                    <div id="minError"></div>
                </div>
                <div class="form-group">
                    <div class="e-float-input">
                        <input type="text" id="regex" name="Regex" regex="^[a-zA-Z]+$" data-regex-message="accepts alphabets only" data-required-message="Required field" required="" data-msg-containerid="regexError">
                        <span class="e-float-line"></span>
                        <label class="e-float-text" for="regex">Regex (accepts alphabets only)</label>
                    </div>
                    <div id="regexError"></div>
                </div>
                <div class="row">
                    <div style="float: left;margin: 0 10% 0 30%">
                        <button id="validateSubmit" class="samplebtn" type="submit" style="height: 35px;">Submit</button>
                    </div>
                    <div>
                        <button id="resetbtn" class="samplebtn" type="reset" style="height: 35px;">Reset</button>
                    </div>
                </div>
            </form>
        </div>
    </div>


<script>
var ele = document.getElementById('container');
if(ele) {
  ele.style.visibility = "visible";
}   
      </script>
<script src="index.js" type="text/javascript"></script>
</body></html>
#container {
    visibility: hidden;
    padding: 10px;
}

#loader {
    color: #008cff;
    height: 40px;
    width: 30%;
    position: absolute;
    top: 45%;
    left: 45%;
}

.e-error,
.e-float-text {
    font-weight: 500;
}

table,
td,
th {
    padding: 5px;
}

.form-horizontal .form-group {
    margin-left: 0px;
    margin-right: 0px;
}

form {
    border: 1px solid #ccc;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.36);
    border-radius: 5px;
    background: #f9f9f9;
    padding: 23px;
    padding-bottom: 20px;
}

.form-title {
    width: 100%;
    text-align: center;
    padding: 10px;
    font-size: 16px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.70);
}