我在将前端用户注册表单作为自定义WordPress主题的一部分时遇到了问题,我需要能够在允许用户注册之前检查是否存在带有ajax请求的电子邮件。
这是JS: 我正在使用jQuery Validate插件,我正在使用addMethod插入.validate调用。这是代码:
function chk_email(value){
var response;
$.ajax({
async: false,
url: ajaxurl,
type: 'POST',
data: {action: 'chk_email', email: value},
dataType: "text",
success: function(msg) {
if (msg>0) {
response = true;
} else{
response = false;
}
}
})
console.log(response);
return response;
}
$.validator.addMethod('chk_email', chk_email, "This email address has already been registered");
$("#adduser").validate({
// debug: true,
rules: {
user_login: {
required: true,
minlength: 3,
nowhitespace: true,
alphanumeric: true
},
first_name: {
required: true,
},
last_name: {
required: true,
},
user_email: {
required: true,
email: true,
nowhitespace: true,
// remote: { url: ajaxurl, type: 'post' }
chk_email: true
},
tel: {
required: true,
phoneUS: true
},
street_address: {
required: true
},
locality: {
required: true
},
region: {
required: true
},
postal_code: {
required: true
},
},
messages: {
user_login: {
required: "Required",
user_login: "A username needs to be atleast 3 charachters long."
},
user_email: {
required: "We need your email address to contact you",
user_email: "Your email address must be in the format of name@domain.com",
nowhitespace: "yeah"
},
},
errorElement: 'span',
errorClass: 'help-inline',
errorPlacement: function(error, element) {
error.insertAfter(element);
},
highlight: function(element) {
var parent = $(element).parents('.control-group');
$(element).addClass('error');
$(parent).addClass('error');
},
unhighlight: function(element) {
var parent = $(element).parents('.control-group');
$(element).removeClass('error');
$(parent).removeClass('error');
}
// debug: true
});
这是我在functions.php文件中使用的PHP:
add_action('wp_ajax_nopriv_chk_email', 'chk_email');
function chk_email(){
if (email_exists($_POST['email']) ){
// return TRUE;
echo 'true';
} else {
// return FALSE;
echo 'false';
}
}
我不太清楚我在这里做错了什么。我很感激任何想法。
答案 0 :(得分:0)
http://docs.jquery.com/Plugins/Validation/Methods/remote
查看概述和示例。
因此,您需要添加chk_email()
选项代替remote
:
remote: {
url: ajaxurl,
type: "post"
}