[英]Unique username with parsley js
I'm trying to use parsley's js custom validator to check for a unique email address on my form. 我正在尝试使用欧芹的js自定义验证器来检查表单上的唯一电子邮件地址。 However it's not stopping the form from submitting when I not matter what I return. 但是,无论我返回什么,它都不会阻止表单的提交。
The ajax request checkEmailExists returns true or false depending on if the email exists Ajax请求checkEmailExists返回true或false取决于电子邮件是否存在
window.Parsley
.addValidator('uniqueUsername', {
requirementType: 'string',
validateString: function(value, requirement) {
$.ajax({
url: "checkEmailExists",
data: {username: value},
dataType: 'json',
method: 'POST',
data: { email: $( "#email" ).val() },
async: false,
success: function(data) {
return data;
}
});
},
messages: {
en: 'This email address already exists!'
}
});
<input type="text" id="email" name="email" placeholder="Email" data-parsley-uniqueUsername data-parsley-required="true" data-parsley-type="email"/>
The promise you are returning must fail or succeed, not succeed with true
or false
. 您返回的承诺必须失败或成功,而不是true
或false
才能成功。
Easiest is probably to use the remote
validator. 最简单的方法可能是使用remote
验证器。
Not relevant, but for idempotent requests like these, you're supposed to use GET
, not POST
. 不相关,但是对于此类幂等请求,应该使用GET
而不是POST
。
As Marc said your promise must fail for succeed and also your validator name can't have capital letters or special characters so try something like this: 正如Marc所说,您的承诺必须失败才能成功,而且您的验证者名称不能使用大写字母或特殊字符,因此请尝试以下操作:
// uniqueUsername validator
window.Parsley.addValidator('uniqueusername', {
validateString: function (value, requirement) {
xhr = $.ajax({
url: "users_list_ajax.php",
dataType: 'json',
method: 'GET',
data: {
action: 'checkUserExists',
username: value
}
});
return xhr.then(function (data) {
console.log((data.isUnique == 0));
if (data.isUnique == 0) {
return true;
} else {
return $.Deferred().reject();
}
});
},
messages: {
en: 'Username already exists!',
ar: 'إسم المستخدم موجود مسبقا'
},
priority: 32
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.