0

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.

2
  • No. $form.validate() is the initialization method for the entire form. $form.valid() is the programmatic trigger for validation of the entire form. They are not the same. After the plugin is initialized, .valid() can be used to programmatically trigger validation on the form or an individual field depending on the jQuery selector target. Otherwise, validation is always automatically triggered on the submit button by default. If your custom rule or method is not being called, that would be something other issue entirely. Commented Feb 7, 2024 at 3:24
  • Since you're tagging the question with ASP and Unobtrusive, I think this is not an issue with the Validation plugin, but with how you're implementing it within the ASP framework. I suggest you edit the question so that it makes more sense in the context of Unobtrusive and ASP. Maybe showing the rendered HTML and JavaScript output would help us narrow this to the root of the breakdown. Commented Feb 7, 2024 at 3:25

1 Answer 1

1

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');
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

Isn't is data-val-custom, instead of data-rule-custom?
No, data-val-xxx does not work....
data-val-xxx is how I got it to finally work. stackoverflow.com/a/44997508/522663

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.