사용자 이름이 이미 있는지 확인하기 위해 knockout.js를 사용하여 사용자 정의 유효성 검사 설정을 얻는 데 문제가 있습니다. 내 이해에서 반환이 true이면 오류가 없으며 그렇지 않으면 오류가 설정됩니다.knockout.js를 사용한 사용자 정의 유효성 검사 규칙
Here's 내가 네트워크 탭을 확인했고 POST가 올바른 값을 반환
//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();
지정 유효성 검사의 예. 값을 사용할 수 있으면 searchType을 반환합니다. 이렇게하면 true이어야하는 searchType == searchType을 비교합니다. 그러나 그 경우는 아닙니다.
내가하려는 일을 수행하는 다른 방법이 있습니까?
갱신
여기에 당신이 항상 정의되지 않은 반환 작성한으로 지금
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