Jquery可复制的输入

时间:2013-01-22 20:14:27

标签: javascript jquery

我已经尝试了很多类型的验证,我正在处理这个表单,我发布了很多关于此表单的问题......

我仍然需要在这个表单上做的只是验证它,例如我已经用'错误'类创建了div,剩下的就是,当有人没有填写错误中的字段时应该滑出和显示..听起来很简单..但输入是可复制的,所以每次我尝试它都会为所有已复制的字段做。

到目前为止,我还没有在电子邮件未经过验证时提交。

有人可以向我展示一个如何验证其中一个可复制字段的示例,例如在'name'中如何验证'name'以确保其中有一个字符,如果没有滑出错误,该字段的错误消息..

这是当前的完整代码JSFiddle:http://jsfiddle.net/36BLm/1/ 以下是仅验证身份证和姓名的代码:http://jsfiddle.net/dawidvdh/7ycUT/

有效身份证号码的示例:85 0929 5266086

主要的JS代码:

    //Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking

//Main Member Variables
var main_input_groups = ["main_group-1"];
var main_age_input_groups = ["main_age_group-1"];
var main_gender_input_groups = ["main_gender_group-1"];
//Main Member Variables

//Dependants Variables
var name_input_groups = ["name-group-1"];
var surname_input_groups = ["surname-group-1"];
var input_groups = ["group-1"];
var age_input_groups = ["age-group-1"];
var gender_input_groups = ["gender-group-1"];
var town_input_groups = ["town-group-1"];
var cell_input_groups = ["cell-group-1"];
var pass_input_groups = ["pass-group-1"];
var email_input_groups = ["email-group-1"];
var relation_input_groups = ["relation-group-1"];
//Dependants Variables

//General Variables
var idNumber;
var cell_values;
var pass_values;
var values;
//General Variables

//Generate variables
var name_fields=[0];
var surname_fields=[0];
var id_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var age_fields=[0,1];
var gender_fields=[0];
var cell_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var passport_fields = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13];
var email_fields=[0];
var town_fields=[0];
var relation_fields=[0];
var code_fields=[0,1,2,3];
//Generate variables

//Main Members Inputs
var main_id_input = "<input class='id' maxlength='1' name='id' type='text' />";
var main_age_input = "<input class='age' name='age' type='text' />";
var main_gender_input = "<input class='gender' maxlength='1' name='gender' type='text' />";
var main_pass_input = "<input class='pass' maxlength='1' name='pass' type='text' />";
var main_con_input = "<input class='cell' maxlength='1' name='cell' type='text' />";
var main_post_code_input = "<input class='post_code code' maxlength='1' name='maincod' type='text' />";
var main_res_code_input = "<input class='res_code code' maxlength='1' name='maincod' type='text' />";
//Main Members Inputs

//Dependants Inputs
var name_input = "<input class='name' name='name' type='text' />";
var surname_input = "<input id='surname' class='surname' name='surname' type='text' />";
var id_input = "<input class='id' maxlength='1' name='id' type='text' />";
var age_input = "<input class='age' name='age' type='text' />";
var gender_input = "<input class='gender' maxlength='1' name='gender' type='text' />";
var town_input = "<input class='town' name='town' type='text' />";
var cell_input = "<input class='cell' maxlength='1' name='cell' type='text' />";
var email_input = "<input class='email' name='email' type='text' />";
var pass_input = "<input class='pass' maxlength='1' name='pass' type='text' />";
var relation_input ='<div>'+
                    "<div class='box1'>"+
                    "<div class='group'>"+
                        "<label class='left'>Spouse</label>"+
                        "<input class='right relationship' type='checkbox' value='spouse' name='relationship' />" +
                    "</div>"+

                    "<div class='group no_b'>"+
                    "<label class='left'>parent</label>"+ 
                    "<input class='right relationship' type='checkbox' value='parent' name='relationship' />" +
                    "</div>"+
                    "</div>"+

                    "<div class='box2'>"+

                    "<div class='group'>"+
                    "<label class='left'>own child</label>"+ 
                    "<input class='right relationship' type='checkbox' value='ownchild' name='relationship' />" +
                    "</div>"+

                    "<div class='group no_b'>"+
                    "<label class='left'>inlaw</label>"+ 
                    "<input class='right relationship' type='checkbox' value='inlaw' name='relationship' />" +
                    "</div>"+
                    "</div>"+

                    "<div class='box3'>"+
                    "<div class='group'>"+
                    "<label class='left'>adopted</label>"+ 
                    "<input class='right relationship' type='checkbox' value='adopted' name='relationship' />" +
                    "</div>"+
                    "<div class='group no_b'>"+
                    "<label class='left'>brother</label>"+ 
                    "<input class='right relationship' type='checkbox' value='brother' name='relationship' />" +
                    "</div>"+
                    "</div>"+

                    "<div class='box4'>"+
                    "<div class='group'>"+
                    "<label class='left'>stepchild</label>"+ 
                    "<input class='right relationship' type='checkbox' value='stepchild' name='relationship' />" +
                    "</div>"+
                    "<div class='group no_b'>"+
                    "<label class='left'>other</label>"+ 
                    "<input class='right relationship' type='checkbox' value='other' name='relationship' />" +
                    "</div>"+
                    '</div>'+
                    "</div>";
//Dependants Inputs

jQuery(document).ready(function(e) {
    //Dependants - populate jquery generated fields
    jQuery(surname_fields).each(function() {
        jQuery(surname_input).appendTo('#surname-group-1');
    });
    jQuery(name_fields).each(function() {
        jQuery(name_input).appendTo('#name-group-1');
    });
    jQuery(email_fields).each(function() {
        jQuery(email_input).appendTo('#email-group-1');
    });
    jQuery(id_fields).each(function() {
        jQuery(id_input).appendTo('#group-1');
    });
    jQuery(age_fields).each(function() {
        jQuery(age_input).appendTo('#age_group-1');
    });
    jQuery(gender_fields).each(function() {
        jQuery(gender_input).appendTo('#gender_group-1');
    });
    jQuery(town_fields).each(function() {
        jQuery(town_input).appendTo('#town-group-1');
    });
    jQuery(cell_fields).each(function() {
        jQuery(cell_input).appendTo('#cell-group-1');
    });
    jQuery(passport_fields).each(function() {
        jQuery(pass_input).appendTo('#pass-group-1');
    });
    jQuery(relation_fields).each(function() {
        jQuery(relation_input).appendTo('#relation-group-1');
    });
    //Dependants

    //Main member - populate jquery generated fields
    jQuery(id_fields).each(function() {
        jQuery(main_id_input).appendTo('#main_group-1');
    });
    jQuery(age_fields).each(function() {
        jQuery(main_age_input).appendTo('#main_age_group-1');
    });
    jQuery(gender_fields).each(function() {
        jQuery(main_gender_input).appendTo('#main_gender_group-1');
    });
    jQuery(passport_fields).each(function() {
        jQuery(main_pass_input).appendTo('#main_pass');
    });
    jQuery(cell_fields).each(function() {
        jQuery(main_con_input).appendTo('#main_cell');
    });
    jQuery(code_fields).each(function() {
        jQuery(main_post_code_input).appendTo('#main_postal_code');
    });
    jQuery(code_fields).each(function() {
        jQuery(main_res_code_input).appendTo('#main_res_code');
    });
    //Main member

    //Cloning Function
    jQuery('#clone').click(function() {
        clone_dependant();
    });
    //Cloning Function

    function clone_dependant() {
        // Store the value of the previous Id to insert the cloned div..
        var oldId = g_counter;
        g_counter++;
        currentdep ='dependant-'+g_counter;
        // Clone the Dependant Div and set a new id
        var $clonedDiv = jQuery('#dependant-1').clone(false).attr('id', currentdep);
        var cell_newDiv = 'cell-group-'+ g_counter;
        var town_newDiv = 'town-group-'+ g_counter;
        var gender_newDiv = 'gender-group-'+ g_counter;
        var age_newDiv = 'age-group-'+ g_counter;
        var id_newDiv = 'group-'+ g_counter;
        var pass_newDiv = 'pass-group-'+ g_counter;
        var name_newDiv = 'name-group-'+ g_counter;
        var surname_newDiv = 'surname-group-'+ g_counter;
        var relation_newDiv = 'relation-group-'+ g_counter;
        var email_newDiv = 'email-group-'+ g_counter;

        // Find div's inside the cloned object and set a new id's
        $clonedDiv.find('#name-group-1').attr('id',"name-group-" + g_counter );
        $clonedDiv.find('#surname-group-1').attr('id',"surname-group-" + g_counter );
        $clonedDiv.find('#group-1').attr('id',"group-" + g_counter );
        $clonedDiv.find('#age-group-1').attr('id',"age-group-" + g_counter );
        $clonedDiv.find('#gender-group-1').attr('id',"gender-group-" + g_counter );
        $clonedDiv.find('#town-group-1').attr('id',"town-group-" + g_counter );
        $clonedDiv.find('#cell-group-1').attr('id',"cell-group-" + g_counter );
        $clonedDiv.find('#pass-group-1').attr('id',"pass-group-" + g_counter );
        $clonedDiv.find('#email-group-1').attr('id',"email-group-" + g_counter );
        $clonedDiv.find('#relation-group-1').attr('id',"relation-group-" + g_counter );
        $clonedDiv.find('#dep_num').html(g_counter);

        // You don't need to Loop thru the inputs to set the value
        $clonedDiv.find('input:checkbox').removeAttr('checked');
        $clonedDiv.find('input[type="text"]').val('');

        // Insert the cloned object 
        $clonedDiv.insertAfter("#dependant-" + oldId);
        name_input_groups.push(name_newDiv);
        surname_input_groups.push(surname_newDiv);
        age_input_groups.push(age_newDiv);
        gender_input_groups.push(gender_newDiv);
        town_input_groups.push(town_newDiv);
        pass_input_groups.push(pass_newDiv);
        relation_input_groups.push(relation_newDiv);
        email_input_groups.push(email_newDiv);
        input_groups.push(id_newDiv);
    }
    //Cloning Function
    //ID Validation
    function validate_Id(values, p) {
            idNumber = values;
            var correct = true;
            if (idNumber.length != 13 || !isNumber(idNumber)) {correct = false;}
            var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
            var today = new Date();
            var id_date = tempDate.getDate();
            var id_month = tempDate.getMonth();
            var id_year = tempDate.getFullYear();
            var currentYear = (new Date).getFullYear();
            var age = Math.floor((today-tempDate) / (365.25 * 24 * 60 * 60 * 1000));
            var fullDate = id_date + "-" + (id_month + 1) + "-" + id_year;
            if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
correct = false;}
            var genderCode = idNumber.substring(6, 10);
            var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
            var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
            var tempTotal = 0;
            var checkSum = 0;
            var multiplier = 1;
            for (var i = 0; i < 13; ++i) {tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
            if (tempTotal > 9) {tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));}
                checkSum = checkSum + tempTotal;
                multiplier = (multiplier % 2 == 0) ? 1 : 2;}
            if ((checkSum % 10) != 0) {correct = false;};
            if (correct) {
                var aig = p.find('.age');
                aig.first().val(Math.floor(age / 10));
                aig.last().val(age % 10);
                p.find('.gender').val(gender);

                return idNumber;
            }
            else {
                console.log(idNumber + "-wrong");
            }
            return false;
        }
    function isNumber(n) {return !isNaN(parseFloat(n)) && isFinite(n);};
//ID Validation

//Basic validation
    function validate_Email(email_values){
        var email_reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if(email_reg.test(email_values) == false) {
            console.log('invalid email');
            return false;
        } else {
            console.log('valid email');
            return true;
        };
    };

    function validate_Cell(cell_values){
        if (cell_values.toString().length != 10) {
            //$('.'+name).slideDown("slow");
            console.log('invalid cell');
        }else if (cell_values.toString().length = 10) {
            //$('.'+name).slideUp("slow");
            console.log('valid cell');
        };
    };

    function validate_Pass(pass_values){
        if (pass_values.toString().length != 13) {
            console.log($(pass_values).toString().length);
            console.log(pass_values);
            //$('.'+name).slideDown("slow");
            console.log('invalid passport');
        }else if (pass_values.toString().length = 13) {
            console.log(pass_values);
            //$('.'+name).slideUp("slow");
            console.log('valid passport');
        };
    };

    function validate_Code(code_values){
        if (code_values.toString().length != 4) {
            console.log($(code_values).toString().length);
            console.log(code_values);
            //$('.'+name).slideDown("slow");
            console.log('invalid passport');
        }else if (code_values.toString().length = 4) {
            console.log(code_values);
            //$('.'+name).slideUp("slow");
            console.log('valid codes');
        };
    };
//Basic Validation
//Multiple Inputs function
$(document).on('keydown', 'input.id, input.cell, input.pass, input.code', function(e) {
     if (e.keyCode == 8) {
       $(this).val('');
       $(this).prev().val('');
       $(this).prev().focus();
    }
});

$(document).on('keyup', 'input.id', function() {
        if (this.value.match(/\d+/)) {
            var $this = $(this);
            if ($this.next('input.id').length) {
                $this.next().focus();
            } else {
                var input_groups = $this.parent();
                $.each(input_groups , function(i){
                    var inpg = input_groups[i];
                    values = $.map($(inpg).children('input'), function(e,i){
                        return $(e).val();
                    }).join('');
                    validate_Id(values, input_groups.parent().parent().parent());
                });
            }
        }
    });
//ID

// 1-22-13: Refactored email validation into separate method
var myInputsModel = [
    { a: 'input.email' }
];

$.each(myInputsModel, function(i, v) {
    $(document).on('blur', v.a, function(a) {
        mySingleFunction(this);
    });
});

function mySingleFunction(el) {
    var $this = $(el);
    var input_groups = $this.parent();
    var isValid = true;
    $.each(input_groups , function(i){
        var inpg = input_groups[i];
        email_values = $.map($(inpg).children('input'), function(e,i){
            return $(e).val();
        }).join('');
        isValid = isValid && validate_Email(email_values, input_groups.parent().parent().parent());
    });
    return isValid;
};  

//CELL
    $(document).on('keyup', 'input.cell', function() {
        if (this.value.match(/\d+/)) {
            var $this = $(this);
            if ($this.next('input.cell').length) {
                $this.next().focus();
            } else {
                var input_groups = $this.parent();
                $.each(input_groups , function(i){
                    var inpg = input_groups[i];
                    cell_values = $.map($(inpg).children('input'), function(e,i){
                        return $(e).val();
                    }).join('');
                    validate_Cell(cell_values, input_groups.parent().parent().parent());
                });
            }
        }
    });
//CELL
//Pasport
    //Multiple Inputs function
    $(document).on('keyup', 'input.pass', function() {
        if (this.value.match(/\d+/)) {
            var $this = $(this);
            if ($this.next('input.pass').length) {
                $this.next().focus();
            } else {
                var input_groups = $this.parent();
                $.each(input_groups , function(i){
                   var inpg = input_groups[i];
                    pass_values = $.map($(inpg).children('input'), function(e,i){
                        return $(e).val();
                    }).join('');
                    validate_Pass(pass_values, input_groups.parent().parent().parent());
                });
            }
        }
    });
//Pasport
//CODE
    $(document).on('keyup', 'input.code', function() {
        if (this.value.match(/\d+/)) {
            var $this = $(this);
            if ($this.next('input.code').length) {
                $this.next().focus();
            } else {
                var input_groups = $this.parent();
                $.each(input_groups , function(i){
                   var inpg = input_groups[i];
                    code_values = $.map($(inpg).children('input'), function(e,i){
                        return $(e).val();
                    }).join('');
                    validate_Code(code_values, input_groups.parent().parent().parent());
                });
            }
        }
    });
//CODE
//Validate General
$('.error').hide();

$(document).on("click", 'input[type="checkbox"]', function() {
    $(this).parent().parent().siblings().find(":checked").removeAttr('checked');
    $(this).parent().siblings().find(":checked").removeAttr('checked');
});
//Multiple Inputs function
//Digits only
jQuery(".id, .cell, .pass").keydown(function(event) {
        if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || 
            (event.keyCode == 65 && event.ctrlKey === true) || 
            (event.keyCode >= 35 && event.keyCode <= 39)) {
                 return;
        } else {
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault(); 
            }   
        }
});
//Digits only
//Get Field Values
var result = {};
var dependants;
var mainmember;
var dep_counter = 0;
function getValues(){
    jQuery('div[class*="mainmember"]').each(function(k, v){
        mainmember = {};
        mainmember['name'] = $(v).find('.name').val();
        mainmember['surname'] = $(v).find('.surname').val();
        mainmember['id'] = ''; 
        $(v).find('.id').each(function(){
          mainmember['id'] += $(this).val(); 
        });
        mainmember['age'] = ''; 
        $(v).find('.age').each(function(){
          mainmember['age'] += $(this).val(); 
        });
        mainmember['gender'] = $(v).find('.gender').val();
        mainmember['townofbirth'] = $(v).find('.town').val();
        mainmember['email'] = $(v).find('.email').val();
        mainmember['contact'] = ''; 
        $(v).find('.cell').each(function(){
        mainmember['contact'] += $(this).val(); 
        });
        mainmember['passport'] = ''; 
        $(v).find('.pass').each(function(){
          mainmember['passport'] += $(this).val(); 
        });
        mainmember['postal'] = $(v).find('.postaladdress').val();

        mainmember['residential_code'] = ''; 
        $(v).find('.res_code').each(function(){
          mainmember['residential_code'] += $(this).val(); 
        });

        mainmember['postal_code'] = ''; 
        $(v).find('.post_code').each(function(){
          mainmember['postal_code'] += $(this).val(); 
        });

        mainmember['residential'] = $(v).find('.residential').val();
        result['mainmember'] = mainmember;
    });

    result['dependants'] = [];
    jQuery('div[class*="dependant"]').each(function(k, v){
        dep_counter++
        dependants = {};
        dependants['name'] = $(v).find('.name').val();
        dependants['surname'] = $(v).find('.surname').val();

        dependants['id'] = ''; 
        $(v).find('.id').each(function(){
          dependants['id'] += $(this).val(); 
        });

        dependants['age'] = ''; 
        $(v).find('.age').each(function(){
          dependants['age'] += $(this).val(); 
        });

        dependants['gender'] = $(v).find('.gender').val();
        dependants['townofbirth'] = $(v).find('.town').val();

        dependants['cell'] = '';
        $(v).find('.cell').each(function(){
          dependants['cell'] += $(this).val(); 
        });

        dependants['email'] = $(v).find('.email').val();

        dependants['passport'] = '';
        $(v).find('.pass').each(function(){
          dependants['passport'] += $(this).val(); 
        });

        dependants['relationship'] = $(v).find('.relationship:checked').val();
        result['dependants'].push(dependants);
    });
};
//Get Field Values

//submit function
jQuery('#submit').click(function(){
    var isValid = true;
    $('input.email').each(function(i, el) {
        isValid = isValid &&
            mySingleFunction(el);
    });
    if (isValid) {
        getValues();
        var jsonData = JSON.stringify(result);
        jQuery.ajax({
            type: "POST",
            url: "mail.php",
            dataType: "json",
            beforeSend: function() {
            },
            data: {parameters: jsonData}
        });
        console.log('Sending error');
        console.log(jsonData);
    } else {
        alert("Please fix validation Email.");
    }
});
//submit function
});

2 个答案:

答案 0 :(得分:1)

您知道,我正在查看电子邮件验证码,并发现它仅在输入只有一封电子邮件(see it in this refiddle)时才有效。

function validate_Email(email_values){
    var email_reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(email_reg.test(email_values) == false) {
        console.log('invalid email');
        return false;
    } else {
        console.log('valid email');
        return true;
    };
};

但是,您一起加入电子邮件,因此正则表达式验证将失败。

function mySingleFunction(el) {
    var $this = $(el);
    var input_groups = $this.parent();
    var isValid = true;
    $.each(input_groups , function(i){
        var inpg = input_groups[i];
        email_values = $.map($(inpg).children('input'), function(e,i){
            return $(e).val();
        }).join('');
        isValid = isValid && validate_Email(email_values, input_groups.parent().parent().parent());
    });
    return isValid;
};  

您需要通过将电子邮件值迭代为数组来重写它。

答案 1 :(得分:1)

$('input.email').each(function(i, el) {
    isValid = isValid &&
        validate_Email($(el).val());
});