Input Form Validation

4 Dec 20244 minutes to read

The Syncfusion® ASP.NET Core UI input and editor controls can be validated by using FormValidator in client side.

How to Validate Syncfusion® ASP.NET Core UI Controls

1.Add the Form component in the Index.cshtml page. Also, declare the Syncfusion® ASP.NET Core TextBox control inside the Form component.

<form id="form-element">
    <div class="form-group">
        <label for="first-name">First Name:</label>
        <ejs-textbox id="firstname" name="FirstName" placeholder="First Name" width="50%"></ejs-textbox>
    </div>
    <div class="form-group">
        <label for="last-name">Last Name:</label>
        <ejs-textbox id="lastname" name="LastName" placeholder="Last Name"  width="50%"></ejs-textbox>
    </div>
    <ejs-button id="submit" content="Submit"></ejs-button>
</form>

2.The following code shows how to perform client side validation using FormValidator inside the script tag.

<script>
    // Sets required property in the FormValidator rules collection
    var options = {
        rules: {
            'FirstName': { required: true },
            'LastName': { required: true },
        },
    };

    // Defines FormValidator to validate the TextBox
    var formObject = new ej.inputs.FormValidator('#form-element', options);

    // Places error label outside the TextBox using the customPlacement event of FormValidator
    formObject.customPlacement = function (element, errorElement) {
        element.parentElement.parentElement.appendChild(errorElement);
    };
    // Form validates the input values using validate method of FormValidator
    document.getElementById("submit").addEventListener('click', function () {
        formObject.validate();
    });
</script>

3.The Form validates the input values and displays the validation message on the FormValidator rules when submitting the form.

Validation Failure:

Validation error status

NOTE

TextBox control supports three types of validation styles. Refer here.

4.You can use the FormValidator rules property to display the custom validation error message for each input control.

<script>
    // sets required property in the FormValidator rules collection
    var options = {
        rules: {
            'FirstName': { required: [true, "Please enter FirstName" ] },
            'LastName': { required: [true, "Please enter LastName" ] },
        },
    };
</script>

Validation message for individual input control

5.You can also use the submit event from FromValidator to validate the form manually.

ASP.NET Core Form Validation Supported Controls

The following section provides the details about the Syncfusion® ASP.NET Core UI controls that are supported with form validation.

See Also