Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validate field where Name attribute contains square brackets?

I am attempting to validate a form that contains fields with name attributes containing square brackets []. It's a requirement that I cannot change the name attribute to something else, and it just seems messy trying to validate via ID or ClassName..

How would I go about validating the w as the following example? As of now it does not work (makes my entire page completely dissappear due to an error.

$("#loginForm").validate({
    rules: {

        login[username]: {
            required: true,
            email: true
        }
    },
    messages: {

        login[username]: {
            required: "Please provide an email",
            email: "Please enter a valid email address"
        }
    }
});
like image 853
Joe Avatar asked Feb 13 '12 17:02

Joe


2 Answers

using login[username] inside a javascript object is not valid syntax. Use quotes around it to make it valid "login[username]"

like image 150
driangle Avatar answered Nov 08 '22 22:11

driangle


Perhaps you could do something like this instead...

HTML:

<input type="text" name="login[username]" class="myRule" />

jQuery:

$(document).ready(function() {

    $('.myRule').rules('add', {
        required: true,
        email: true,
        messages: {
            required: "Please provide an email",
            email: "Please enter a valid email address"
        }
    });

});

Alternatively, you do not need to add or use classes, just use the proper selector to target the appropriate input element.

$(document).ready(function() {

    $('input[name=login\\[username\\]]').rules('add', {
        required: true,
        email: true,
        messages: {
            required: "Please provide an email",
            email: "Please enter a valid email address"
        }
    });

});

http://docs.jquery.com/Plugins/Validation/rules

like image 33
Sparky Avatar answered Nov 08 '22 23:11

Sparky