jQuery动态地为n个字段添加验证规则


jQuery dynamically add validation rules to n-number of fields

我使用jQuery验证插件来验证表单。表单字段是动态生成的。我有一个电子邮件:

<input type="text" name="customer_email_<?=$i?>" value="" id="customer_email_<?=$i?>" />

这个输入字段在php循环中,可以生成n次。其目的是检查输入的电子邮件是否唯一。当用户在生成的任何字段中输入内容时,我将发送一个AJAX调用,该调用将在数据库中检查电子邮件是否唯一。

    var pass_count_array = [<?=$js_array?>]; // generated by php
jQuery.each(pass_count_array, function(index, p) {
    //check if the e-mail is unique
    jQuery.validator.addMethod("unique_email_"+p, function(value, element) {
        return check_unique_email(p);
    });  

    var current_email = "customer_email_"+p;
    jQuery("#tair_form").validate({
        rules : {
            current_email: {
                "unique_email_"+p : true
            }
     });        
});

上面的代码循环遍历所有字段,添加了一个自定义验证方法unique_email_1、unique_email_2等。这里的问题是验证规则不接受:

"unique_email_"+p : true

如何将自定义验证方法应用于每个电子邮件输入字段?

将一个类附加到email字段,这样您就不必按id搜索,而是按类分组,这样您只需对整个类对象应用检查。

.each()为例,循环它们,并在需要时触发警报。

这个呢

<input type="text" name="customer_email" value="" id="<?=$i?>" />
$(function(){
    $("input[name=customer_email]").change(function(){
        var email = $(this).attr("id");
        if(check_unique_email(email)==true){
            //callback when email is unique
        }else{
            //callback when email is not unique
        }
    });
});