Reputation: 745
I'm using the jQuery plugin jQuery Validation for the validation of form fields. I've written some custom rules as well as using default rules and they all work fine at the moment. If a field doesn't validate, the form cannot be submitted until the offending field validates.
However, I have just been asked to make a change to the validation for a particular field using a custom rule, such that the validation rules stay the same and the validation error message appear if the field does not validate but that the form can still be submitted.
Is there a native way to allow for such a request on a per field/rule basis? If not, what would be the best way to add this functionality within the framework of jQuery Validation?
Upvotes: 1
Views: 203
Reputation: 98738
"I have just been asked to make a change to the validation for a particular field using a custom rule, such that the validation rules stay the same and the validation error message appear if the field does not validate but that the form can still be submitted."
The whole point of the jQuery Validation plugin is to block submission based on your specified rules.
The built-in addMethod
method works by displaying an error (blocking submission) when your custom function returns false
. To allow submission, this function must return true
, but then no message would be displayed.
I don't see how what you request is possible without rewriting the plugin.
Otherwise, a simple workaround would be to write a separate function attached to the one field's blur or click event handler that toggles a <label>
in the same location as a validation error would appear. Something like...
$('input#myField').on('blur', function() {
// your custom validation
if ( /* some arbitrary rule */ ) {
// failed your test, show message
$('label#myLabel').show();
} else {
// passed your test, hide message
$('label#myLabel').hide();
}
});
Although, I recommend against doing any of this as it runs counter to the way the average user expects a form to behave.
Upvotes: 1