I have an ASP.NET project with some views with forms. I wanted to change the trigger for the validation of the inputs. This code is used to trigger the validator on keyup and not out of focus.
$(document).ready(function () {
var $validatr = $('form').data('validator');
var settngs = $validatr.settings;
settngs.onkeyup = function (element, eventType) {
if (!$validatr.element(element))
{
$(this.currentForm).triggerHandler("invalid-form", [this]);
}
};
settngs.onfocusout = false;
});
Problem
On some views I get this error:
TypeError: $validatr is undefined, var settngs = $validatr.settings;
And the validation error appear only on out of focus. I tried to get the validator also with this code, but also failed:
var $validatr = $('form').validate()
The controller, model and views are pretty much the same. Just the names of the inputs changes.
UPDATE If I use this code:
$(document).ready(function () {
var $validatr = $('form').validate();
var settngs = $validatr.settings;
console.log('settings:'); //I get an output
console.log(settngs); //I get an output
settngs.onkeyup = function (element, eventType) {
console.log(element); //I do not get any message here
console.log(eventType); //I do not get any message here
if (!$validatr.element(element)) {
console.log('if not validator');
$(this.currentForm).triggerHandler("invalid-form", [this]);
}
else {
console.log('else not validator');
}
};
// onload initial validation
$("form").validate().elements().each(function () {
if (!$validatr.element($(this))) {
console.log($(this)[0].name + ': initial if not validator');
$(this.currentForm).triggerHandler("invalid-form", [this]);
}
});
});
This are the settings returned to console:
errorClass:"error"
errorContainer:Object[]
errorElement:"label"
errorLabelContainer:Object[]
focusCleanup:false
focusInvalid:true
groups:Object:{}
ignore:":hidden"
ignoreTitle:false
messages:Object:{}
onsubmit:true
rules:Object:{}
validClass:"valid"
highlight:function(element,:errorClass,:validClass)
onclick:function(element)
onfocusin:function(element)
onfocusout:function(element)
onkeyup:function(element,:eventType)
unhighlight:function(element,:errorClass,:validClass)
SOLUTION
At the end this was the solution: MVC 5 Losing validator
$('form').data('validator')will get validator if you have properly initialized jquery and unobtrusive validation. If you are still experiencing an issue, please post more of your code (including layout page, etc.)