我無法獲得自定義驗證規則設置與knockout.js檢查用戶名是否已經存在。根據我的理解,如果返回是真的,那麼就沒有錯誤,否則就會設置錯誤。自定義驗證規則與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("https://stackoverflow.com/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。但是,事實並非如此。
有沒有其他方法可以完成我想要做的事情?
更新
這裏是我的現在,你已經寫它總是返回undefined
function checkValue(val, searchType, callback) {
var callback = function(data) {
return true;
}
$.post("https://stackoverflow.com/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();
謝謝,得到它的工作!你爲我清理了很多,我非常感激。 – user1443519