开发者

Jquery validator vs. bidimensional arrays

I'll just start with the example of my problem:

<form>
    <input name="course[0][name]" />
    <input name="course[0][type]" />

    <input name="course[1][name]" />
    <input name="course[1][type]" /&g开发者_如何学运维t;

    ...
    ...
</form>

obs: this is, of course, simplified.

So...how can i validate those since i can't predict the name? Is there a way to use regular expressions or something? utopic example:

rules: {
    /course\[([0-9]+)\]\[name\]/: {
        required: true
    }
}

I couldn't find the solution in the documentation since its a bit confusing. thank you (:


As an alternative you can do something like this

$.validator.addClassRules({
    inputName: {
        required: true,
        minLength: 5
    },
    inputType: {
        required: true,
        remote: "remoteurl"
    }
});
<input name="course[0][name]" class="inputName"/>
<input name="course[0][type]" class="inputType"/>


So, I did a little bit of searching, and it looks like the keys in the rules object are simple jQuery selectors. According to this question, there is a regex filter which can be used. Between the two, your regex above should work.


Original idea:

... you don't need to predict them, your server already knows them. Just output that number into a script tag and then loop. Heck, you can even have the server loop for you.

If that is not an option, then you can use jQuery:

var rules = {
 // simple rule, converted to {required:true}
 name: "required",
 // compound rule
 email: {
   required: true,
   email: true
 }
 // whatever
}
// obviously, for just required, there are easier ways
var checkRules = {required:true}; 
$('#form-id input').each(function(i, elem)
{
   /check\[\d\]\[(name|type)\]/.test(elem.name)
   rules[elem.name] = checkRules
});


More a workaround: By default, you can specify a class named required on the fields that are required.


Another option would be to fill up the rules options programmatically (complete code in this gist):

Assuming a simple example HTML with the following body:

<body>
    <form id="example">
    <input  name="course[0][name]" />
    <input  name="course[0][type]" />

    <input  name="course[1][name]" />
    <input  name="course[1][type]" />

    <input type="submit" name="some_name" value="Go" id="some_name">
    </form>
</body>

The corresponding javascript to determine matching elements via filter:

    $(document).ready(function(){

        var options = { rules : {} }

        // put your regex in here ...
        var courses = $('input').filter(function(){
            return this.name.match(/course\[([0-9]+)\]\[name\]/);
        });

        for (var i = courses.length - 1; i >= 0; i--){
            options["rules"][courses[i].name] = { required : true };
        };

        $("#example").validate(options);
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜