Perform custom validation using FormValidator

26 Oct 20223 minutes to read

This section explains how to perform custom validation on the NumericTextBox using FormValidator. The NumericTextBox will be validated when the value changes or the user clicks the submit button. Validation can be performed by adding custom validation in the rules collection of the FormValidator.

<form id="form-element">
    @Html.EJS().NumericTextBox("numeric").Min(10).Max(100).Change("onChange").Placeholder("numeric").Created("onCreate").StrictMode(false).FloatLabelType(Syncfusion.EJ2.Inputs.FloatLabelType.Always).Render()
    @Html.EJS().Button("submit_btn").Content("submit").Render()
</form>

<script>
    function onCreate() {
        document.getElementById(this.element.id).setAttribute("name", "numericRange");
    }
    function onChange(args) {
        if (numeric.value != null) {
            formObject.validate("numericRange");
        }
    }
    var customFn = function (args) {
        if (numeric.value >= 10 && numeric.value <= 100) {
            return true;
        }
        else {
            return false;
        }
    };
    // sets required property in the FormValidator rules collection
    var options = {
        rules: {
            'numericRange': { required: [true, "Number is required"] },
        },
    };
    // defines FormValidator to validate the MaskedTextBox
    var formObject = new ej.inputs.FormValidator('#form-element', options);

    // places error label outside the MaskedTextBox using the customPlacement event of FormValidator

    formObject.customPlacement = function (element, errorElement) {
        element.parentNode.parentNode.appendChild(errorElement);
    };

    formObject.addRules('numericRange', { range: [customFn, "Please enter a number between 10 to 100"] });
    document.getElementById("submit_btn").addEventListener('click', function () {
        formObject.validate("numericRange");
        var ele = document.getElementById('numeric');
        // checks for incomplete value and alerts the formt submit
        if (ele.value !== "" && ele.value >= 10 && ele.value <= 100) {
            alert("Submitted");
        }
    });
</script>

<style>
    .e-numeric.e-control-wrapper {
        margin-bottom: 20px;
    }

    label.e-error {
        margin-top: -50px;
    }
</style>
public ActionResult customValidation()
{
    return View();
}

Output be like the below.

NumericTextBox Sample