我无法使用 knockout.js 设置自定义验证规则以检查用户名是否已存在。据我了解,如果返回为真,则没有错误,否则设置错误。
这是自定义验证的示例
//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 应该是真的。然而,事实并非如此。
还有其他方法可以完成我想做的事情吗?
更新
这是我现在所拥有的
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();