JQuery Validation Plugin:使用自定义Ajax方法

nam*_*tax 3 jquery jquery-plugins jquery-validate

如果可能的话,寻找Jquery表单验证插件的一些帮助.

我通过对我的数据库进行ajax调用来验证模板的电子邮件字段,该数据库检查电子邮件字段中的文本当前是否在数据库中.

    // Check email validity on Blur
       $('#sEmail').blur(function(){
       // Grab Email From Form
       var itemValue = $('#sEmail').val();
        // Serialise data for ajax processing
        var emailData = {
            sEmail: itemValue
        }
        // Do Ajax Call
         $.getJSON('http://localhost:8501/ems/trunk/www/cfcs/admin_user_service.cfc?method=getAdminUserEmail&returnFormat=json&queryformat=column', emailData, function(data){

                    if (data != false) {
                        var errorMessage = 'This email address has already been  registered';
                    }
                    else {
                        var errorMessage = 'Good'
                    }
                })
    });
Run Code Online (Sandbox Code Playgroud)

我想做的是将此调用纳入我的JQuery Validation Plugin的规则中......例如

    $("#setAdminUser").validate({
      rules:{
             sEmail: {
                  required: function(){
                  // Replicate my on blur ajax email call here
                 }                  
             },
            messages:{
                sEmail: {
                    required: "this email already exists"       

            }
        });
Run Code Online (Sandbox Code Playgroud)

想知道是否有实现这个目标?非常感谢

the*_*ine 15

你正在做一个AJAX请求,ergo:当你的自定义验证器返回true或false时,验证已经完成.

您将需要使用异步.另请参阅此文章:如何让jQuery执行同步而非异步的Ajax请求?

假设我们有一个自定义验证来检查Unique Mobile,所以我们将添加一个新方法,以检查unqiue Mobile no:

jQuery.validator.addMethod("uniqueMobile", function(value, element) {
    var response;
    $.ajax({
        type: "POST",
        url: <YOUR SERVER SCRIPT/METHOD>,
        data:"mobile="+value,
        async:false,
        success:function(data){
            response = data;
        }
    });
    if(response == 0)
    {
        return true;
    }
    else if(response == 1)
    {
        return false;
    }
    else if(response == 'logout')
    {
        return false;
    }
}, "Mobile is Already Taken");
Run Code Online (Sandbox Code Playgroud)

  • 随时都有兄弟.. !! :) (3认同)