问题描述
检查这个小提琴:
我正在尝试做两件事:
第一:在字段为空时不进行验证.我知道有一个onlyif选项..但是有什么更简单的方法吗?
First: Dont validate when the field is empty. I know there is a onlyif option.. but is there something easier?
第二:当我单击提交"时,我需要一些东西来运行验证(如果您对我的小提琴进行了测试,则会弹出错误消息,但不会应用errorClass css)
Second: I need something to run the validation when i click on submit (If you test my fiddle, the error messages will pop, but wont apply the errorClass css)
谢谢:D
css:
input.error {
color: red;
border-color: red;
}
js:
ko.validation.configure({
insertMessages: false,
decorateElement: true,
errorElementClass: 'error',
messagesOnModified: false
});
function SignInViewModel() {
var self = this;
self.userName = ko.observable().extend({
required: true
});
self.password = ko.observable().extend({
required: true
});
self.errors = ko.validation.group(self);
self.login = function (e) {
if (self.errors().length == 0) {
alert('No errors');
} else {
this.errors().forEach(function(data) {
alert(data);
});
//self.errors.showAllMessages(true);
}
}
}
$(function () {
ko.applyBindings(new SignInViewModel());
});
html:
<form>
<fieldset>
<legend>User: <span data-bind='text: errors().length'></span> errors</legend>
<label>User name: <input data-bind='value: userName' type="text"/></label><br/>
<label>Password: <input data-bind='value: password' type="password"/></label>
</fieldset>
<button type="button" data-bind='click: login'>Login</button>
</form>
推荐答案
第一个解决方案将完成您要求的90%.在用户点击提交"或删除之前填充的字段之前,它不会显示任何验证.一旦他们打破密封(可以这么说),他们将收到该领域的实时验证反馈.这是我要使用的解决方案,因为它是敲除验证的预期行为.
The first solution will do 90% of what you are asking. It will not display any validation until the user hits submit, or until they delete a previously populated field. Once they break the seal (so to speak), they will receive real time validation feedback for that field. This is the solution I would use because it is how knockout validation was intended to behave.
self.login = function (e) {
if (self.errors().length > 0) {
self.errors.showAllMessages(true);
this.errors().forEach(function(data) {
alert(data);
});
}
}
如果由于某种原因您必须推迟所有验证反馈直到它们单击,那么您可以将isModified标志弄乱以获得所需的行为.不过,对我来说似乎有点糊涂.
If for some reason you have to defer all validation feedback until they click, then you could mess with the isModified flag to get the behavior you want. It seems a little kludgy to me though.
ko.extenders.deferValidation = function (target, option) {
if (option) {
target.subscribe(function(){
target.isModified(false);
});
}
return target;
};
self.userName = ko.observable().extend({
required: {message: 'User name is required' },
deferValidation: true
});
self.password = ko.observable().extend({
required: {message: "Password is required" },
deferValidation: true
});
这篇关于敲除验证-空时不验证输入+提交时求值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!