我在使用 knockout.js 设置自定义验证规则来检查用户名是否已存在时遇到问题。根据我的理解,如果返回 true 则没有错误,否则设置错误。
Here's自定义验证的示例
//val is the username in question and searchType is the type of search(username or email)
function checkValue(val, searchType){
if(searchType == 'userName'){
$.post("/users/check_if_exists",{ 'type':'username', 'value': val },function(data) {
var info = JSON.parse(data);
if(info.username_availability == "available"){
return searchType;
//I know this is working because I've alerted the searchtype here and it displays properly
}
else{
return "unavailable";
}
});
}
}
ko.validation.rules['checkIfExists'] = {
validator: function (val, searchType) {
return searchType == checkValue(val, searchType); //if the username is availble, the searchType is returned back so it would return searchType == searchType which should be true meaning there are no errors
},
message: 'This username is taken, please select another.'
};
ko.validation.registerExtenders();
我检查了网络选项卡,POST 返回了正确的值。如果该值可用,我将返回 searchType。这样,它比较 searchType == searchType 应该为 true。然而,事实并非如此。
还有其他方法可以完成我想做的事情吗?
更新
这是我现在所拥有的
function checkValue(val, searchType, callback) {
var callback = function(data) {
return true;
}
$.post("/users/check_if_exists", { 'type':'username', 'value': val }, function(data) {
info = JSON.parse(data);
if(info.username_availability == "available"){
callback(true);
} else {
callback(false);
}
});
}
ko.validation.rules['checkIfExists'] = {
async: true,
validator: function (val, searchType) {
alert(checkValue(val, searchType));//returns undefined
return checkValue(val, searchType);
},
message: 'This username is taken, please select another.'
};
ko.validation.registerExtenders();
最佳答案
ko.validation 调用您的验证函数。 关于将成功/失败状态传递回 ko.validation 的方式,验证函数有两种类型:直接返回真/假方式,或“异步”方式。
异步方式的存在只是因为 $.ajax 存在,它基本上就是这样:不是返回一个值(这是不可能的,因为你正在使用 $.ajax 调用),你必须在 ajax 之后以某种方式通知 ko.validation响应返回到浏览器,对吗?
因此,编写这个库的聪明人会使用一个额外的参数(即函数(回调))调用您的验证函数,您必须在响应可用时调用该函数。
function checkValue(val, searchType, callback){
if(searchType == 'userName'){
$.post("/users/check_if_exists",{ 'type':'username', 'value': val },function(data) {
var info = JSON.parse(data);
if(info.username_availability == "available"){
callback(true);
//I know this is working because I've alerted the searchtype here and it displays properly
}
else{
callback(false);
}
});
}
}
ko.validation.rules['checkIfExists'] = {
async: true,
validator: checkValue,
message: 'This username is taken, please select another.'
};
ko.validation.registerExtenders();
关于javascript - 使用 Knockout.js 自定义验证规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18390811/