我有一个ASP.NET项目,其中包含一些带有表单的视图。我想更改输入验证的触发器。此代码用于在keyup上触发验证器而不是失焦。
$(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;
});
问题
在某些观看中,我收到此错误:
TypeError: $validatr is undefined, var settngs = $validatr.settings;
验证错误仅在焦点外出现。 我尝试使用此代码获取验证器,但也失败了:
var $validatr = $('form').validate()
控制器,模型和视图几乎相同。只是输入的名称发生变化。
更新 如果我使用此代码:
$(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]);
}
});
});
这是返回控制台的设置:
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)
解
最后这是解决方案: MVC 5 Losing validator
答案 0 :(得分:0)
除了上面的评论之外,JavaScript区分大小写,Validate()
应为validate()
。
var $validatr = $('form').validate();
见jsFiddle。如果您在Chrome中使用inspect,或在FireFox中使用FireBug,您将在控制台中看到输出并且没有错误。
更新1 - 我已经扩展了jsFiddle以模拟您在onkeyup
上验证所需的效果。如果您this jsFiddle works,请告诉我。我还为所有元素添加了初始验证。
// 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]);
}
});