Reputation: 776
I want to validate my form in real-time (on input) using this jquery plugin : https://jqueryvalidation.org/rules/?
This is an example of my current validation function:
(function(ns, window, document, $, undefined) {
var $form;
ns.init= function(){
$form = $('#formQA');
$form.validate({
rules : {
QResponse : {
required: function (element) {
if ($(element).is(":visible")) {
return true;
}
return false;
} ,
maxlength: 255,
minlength: 2
}
}
})
}
})(home.createNS('home.qa.validation', false), window, document, jQuery);
Upvotes: 0
Views: 1050
Reputation: 98738
By default, it validates on the keyup
event. However, validation is "lazy", not "eager", which means that no validation happens until after the first click of submit. So you'll have to tweak some settings.
$form.validate({
rules : {
// rules
},
onfocusout: function(element) {
this.element(element); // triggers validation
},
onkeyup: function(element, event) {
this.element(element); // triggers validation
}
});
Your code:
required: function (element) {
if ($(element).is(":visible")) {
return true;
}
return false;
}
You do not need to test for visibility. By default, the plugin will dynamically ignore any hidden field. Just set required
to true
and let the rest happen.
Upvotes: 2