嗨,我是 Knockoutjs 的新手,我想发布一个表单,例如我有一个电子邮件地址,要求电子邮件地址必须是唯一的。
在服务器上,我检查电子邮件地址是否唯一,然后返回一个validationjson 类,例如
{ isEmailUnique: false, isPasswordStrongEnough: true; }
我如何通过 knockoutjs 验证以简洁的方式显示这些错误?
嗨,我是 Knockoutjs 的新手,我想发布一个表单,例如我有一个电子邮件地址,要求电子邮件地址必须是唯一的。
在服务器上,我检查电子邮件地址是否唯一,然后返回一个validationjson 类,例如
{ isEmailUnique: false, isPasswordStrongEnough: true; }
我如何通过 knockoutjs 验证以简洁的方式显示这些错误?
I would use two different server side validators for this, since they affect different observables in the view model.
Originally taken from the knockout validation readme
ko.validation.rules['isEmailUnique'] = {
validator: function(val, param){
var isValid = true;
$.ajax({
async: false,
url: '/validation/isEmailUnique',
type: 'POST',
data: { value: val, param: param },
success: function(response){
isValid = response === true;
},
error: function(){
isValid = false; //however you would like to handle this
}
});
return isValid;
},
message: 'The Email is not unique'
};
Then on the server you need to create an endpoint that accepts POST requests where you perform your lookup and then return true or false depending on the result of the query.
To use the above validator
this.email = ko.observable()
.extend({
isEmailUnique: {
message: 'Something else perhaps? It will override the message in the validator'
}
});
You can use the very same thing for the password strength validation.
Using validators like this will fire validation when the observable changes, which can be a useful way to do validation.
我有点晚了,但是为了我的 2 美分,我会采取更通用的方法,例如从您的服务器端点(例如 /Register)返回一个标准的 JSON 序列化 AjaxResult 类,其属性包括 Data(使用的任意容器)例如,要与映射插件重新绑定的更新模型),以及验证消息字符串的集合等。然后您可以拥有一个绑定到 ObservableArray 的 HTML 验证摘要并推送/映射来自您的消息Ajax 结果进了那里。这基本上就是我一直在用 Knockout 做的事情,而且效果很好。