How to trigger my custom validation method from validate() or valid()

161 Views Asked by At

I can validate my form by calling $form.validate() and $form.valid(). And so presumably these functions are called automatically when submitting a form.

But my question is: If I have a custom validation function, how can I cause it to be called automatically when these validation methods are called? That is, I want my validation function to be called when the form is submitted, but also if $form.validate() and $form.valid() are called manually.

1

There are 1 best solutions below

3
VDWWD On

You can use $.validator.addMethod. So if you have an input that needs a custom validation rule, you can add the custom method to the validation process.

<label for="MyCustomValidation">My Custom Validation</label>
<input type="text" name="MyCustomValidation" id="MyCustomValidation" data-val="true" data-val-required="This field is required." data-rule-custom="Custom validator triggered." class="form-control" />
<span data-valmsg-for="MyCustomValidation" data-valmsg-replace="true"></span>

And then in javascript

function MyCustomValidator() {
    if (typeof $.validator === 'undefined')
        return;

    $.validator.addMethod('custom', function (value, element) {
        var result = false;
        this.elementid = element.id;

        if (value === 'custom') {
            result = true;
        }

        return this.optional(element) || result;

    }, function () {
        return $('#' + this.elementid).attr('data-rule-custom');
    });
}