I would like to add a custom rule to jQuery Validate that allows me to do a check and some specific actions according to the event triggering it.
For example for an email, after the 1st submit of the form (blocked by Validate):
- if the event is a submit:
- check if the email already exists (ajax call)
- if the email domain "looks like" a known domain name: suggest it (popup, or blocking the form validation once)
- if its a keyup:
- if the email domain "looks like" a known domain name: do some passive suggestions
- if there are some common misstypings, suggest the correct spelling
The field I'm targeting already has some other rules that will trigger on all default trigger events of jQuery Validate (after submission: keyup, focusout etc.) and I want to keep it this way. (for the email example: run an email regex)
For this reason, I would like to use the event triggering the rule check to determine my custom rule's actions.
I wanted first to pass the event through the rules params but couldn't figure out where to get it from.
My current solution for this is as follows:
set the event on some variable when it's caught by validate and keep the default validation going
var validationEvent;
$('#myForm').submit(function(event) {
event.stopPropagation();
event.preventDefault();
validationEvent = event;
}).validate({
onkeyup: function(element, event) {
validationEvent = event;
$(element).valid();
},
rules: {
email: {
required: true,
myCustomFunction: true,
email: true
}
}
});
My custom function would then look like this:
$.validator.addMethod("myCustomFunction", function(value, element, params) {
if (validationEvent == undefined) {
return true;
}
if (validationEvent.type == "submit") {
// do something
}
if (validationEvent.type == "keyup") {
// do something else
}
});
This feels bad to do (and is probably bad) and i'd like to make it good.
my best guess would be to somehow pass the event through the rules params like this:
$('#myForm').validate({
rules: {
email: {
myCustomFunction: event
}
}
});
$.validator.addMethod("myCustomFunction", function(value, element, params) {
if (params.type == "submit") {
// do something
}
}
Is there a possibility to do it like this, or through another way?