2

我在将前端用户注册表单作为自定义 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';
  }
}

我不太确定我在这里做错了什么。我会很感激任何想法。

4

1 回答 1

0

http://docs.jquery.com/Plugins/Validation/Methods/remote

查看概述和示例。

因此chk_email(),您将添加到remote选项中,而不是 :

remote: {
    url: ajaxurl,
    type: "post"
}
于 2012-06-19T05:38:21.647 回答