Search code examples
jqueryjquery-validateasp.net-core-mvcunobtrusive-validation

Custom Validation in jQuery Unobtrusive Validation Without Field Name


Is it possible, using jQuery unobtrusive validation, to specify a custom validation function that is not bound to a specific field? I mean, a validation function that is triggered when the form is validated, but not targeted at a specific form field. This is in the context of ASP.NET Core validation, and I would prefer not to add any code to the form submit handler. Essentially, I would like to keep the default behavior when I click on a submit button, but besides the usual field-oriented validation also do bespoke ("global") validation too.


Solution

  • One way to achieve this is to have an hidden field with validation attributes:

    <input type="hidden" id="val" name="val" data-val="true" data-val-custom="My custom error message" />
    

    Then hook it to unobtrusive validation:

    $.validator.addMethod('custom', function (value, element, params) {
        //whatever
        return false;
    });
    $.validator.unobtrusive.adapters.addBool('custom');
    

    This way it will appear as if it is general, not field-specific.