Perform custom validation using FormValidator

17 Feb 20223 minutes to read

To perform custom validation on the MaskedTextBox use the FormValidator along with custom validation rules.

In the following example, the MaskedTextBox is validated for invalid mobile number by adding custom validation in the rules collection of the FormValidator.

<form id="form-element">
    @Html.EJS().MaskedTextBox("mask1").Mask("000-000-0000").Placeholder("Mobile Number").FloatLabelType(Syncfusion.EJ2.Inputs.FloatLabelType.Always).Created("onCreate").Render()
    @Html.EJS().Button("submit_btn").Content("Button").Render()
</form>

<script>

    var customFn = function (args) {
        var argsLength = args.element.ej2_instances[0].value.length;
        if (argsLength != 0) {
            return argsLength >= 10;
        }
        else return true;
    };
    var custom = function (args) {
        var argsLength = args.element.ej2_instances[0].value.length;
        if (argsLength == 0) {
            return 0;
        }
        else {
            return argsLength;
        }
    };
    // sets required property in the FormValidator rules collection
    var options = {
        rules: {
            'mask': { numberValue: [customFn, 'Enter valid mobile number'] },
        },
    };
    // defines FormValidator to validate the MaskedTextBox
    var formObject = new ej.inputs.FormValidator('#form-element', options);
    formObject.addRules('mask', { maxLength: [custom, 'Enter mobile number'] });

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

    formObject.customPlacement = function (element, errorElement) {
        document.querySelector("#mask1").parentNode.appendChild(errorElement);
    };
    document.getElementById("submit_btn").addEventListener('click', function () {
        formObject.validate("mask");
        var ele = document.getElementById('mask1');
        // checks for incomplete value and alerts the formt submit
        if (ele.value !== "" && ele.value.indexOf(ele.ej2_instances[0].promptChar) === -1) {
            alert("Submitted");
        }
    });

    function onCreate() {
        document.getElementById(this.element.id).setAttribute("name", "mask");
    }
</script>
public ActionResult howto()
{
    return View();
}

Output be like the below.

MaskedTextBox Sample