Validate multidimensional array using jQuery validate plugin

早过忘川 提交于 2019-12-22 13:56:33

问题


I have created form like this :

<form>
    <div class='row user">
         <div class="col-md-6 col-sm-6 input-group">
                <input type="text" class="form-control" name="user[0][name]" placeholder="Enter speaker's name">
         </div>
         <div class="col-md-6 col-sm-6 input-group">
                <span class="input-group-addon" id="basic-addon1"><i class="fa fa-envelope"></i> </span>
                <input type="text" class="form-control" name="user[0][email]"  placeholder="Email">
         </div>
    </div>
    <button onclick="addMoreUser()" class="add-more">Add User</button>
</form>

On Clicking "Add User" button it will add one more div with class "user" and it's input as user[1][name] and user[1][email].

I want to validate email and name as required and email must be valid email format. For validation the code goes like here:

 $('form').validate({
    rules : {
        "user[][name]" : {
            required: true
        },
        "user[][email]" : {
            email: true,
            required : true,
        },
    },
    messages :{
        "user[][name]" : {
            required: "Name is Mandatory"
        },
        "user[][email]" : {
            email: 'Email must be valid email address',
            required : 'Email is Mandatory',
        },
    }
});

Can anyone please help me how to validate such multidimensional array using validate plugin? Any help would be appreciated.


回答1:


First select all input elements that start with user. Use a jQuery .filter() to find all elements that end with name and email. Then use a jQuery .each() along with the .rules() method to loop through and apply the rules.

var user = $('input[name^="user"]');

user.filter('input[name$="[name]"]').each(function() {
    $(this).rules("add", {
        required: true,
        messages: {
            required: "Name is Mandatory"
        }
    });
});

user.filter('input[name$="[email]"]').each(function() {
    $(this).rules("add", {
        email: true,
        required: true,
        messages: {
            email: 'Email must be valid email address',
            required : 'Email is Mandatory',
        }
    });
});

DEMO: jsfiddle.net/upq6uk0h/




回答2:


When targeting more than one element, you must also use the jQuery .each() method.

 $('.form-control').each(function () { 
    $(this).rules("add", {
        required: true
    });
});


来源:https://stackoverflow.com/questions/41628897/validate-multidimensional-array-using-jquery-validate-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!