Reputation: 1629
my code has to be like this:
rules: {
jform[name]: {
required:true,
minlength:5,
maxlength:15
},
how should I use those square brackets? There are a lot of answers regarding this subject found on this website and on google, but not particularly for this one.
Upvotes: 0
Views: 7055
Reputation: 179046
I can't accurately answer your question as it stands right now, because you're asking how to use invalid syntax, which is impossible as it's invalid.
However, what I can do is explain how JSON works in JavaScript and hope that it covers your problem:
{}
is an object literal//this creates a new object
a = {};
//so does this
a = new Object();
[]
is an array literal//this creates a new array
a = [];
//so does this
a = new Array();
.
and []
notation://these are the same
a.b = c;
a['b'] = c;
a = {
//any character you can use for a variable name can be
//used to instantiate an object without quotes
b: c,
//special characters need to be quoted
"foo bar baz": "fizz buzz"
};
Your original syntax of:
rules: {
jform[name]: {
required:true,
minlength:5,
maxlength:15
}
is invalid because you can't use [
and ]
chars in a variable name, however you could use a string for the literal value:
rules: {
"jform[name]": {
required:true,
minlength:5,
maxlength:15
}
...which would be accessed as:
rules["jform[name]"]
but it appears that you want to access the data as:
rules.jform[name]
which would need to be set as:
rules: {
jform: {}
}
...more code...
rules.jform[name] = {rules: {
required:true,
minlength:5,
maxlength:15
};
Upvotes: 7
Reputation: 816
obj = {
"rules" : {
"jform" : {
"name" : {
required:true,
minlength:5,
maxlength:15
}
}
}
},
you can now access values like this
obj[rules][jform][name]
Upvotes: 3
Reputation: 227240
I'm guessing you want the value of jform[name]
to a key in the object. You can't use variables as keys when declaring an object literal. You'll have to add this key as another statement.
Example:
var data = {
rules: {
}
};
data.rules[jform[name]]= {
required:true,
minlength:5,
maxlength:15
};
If you want the key to literally be jform[name]
, then you need to use quotes around the key.
rules: {
"jform[name]": {
required:true,
minlength:5,
maxlength:15
}
}
Upvotes: 3
Reputation: 664538
Do you mean JSON? Or JavaScript Object literals? Please remove the buzzword "jQuery" from your question.
If you want a property name with (square) brackets, you can either do
rules = {
"jform[name]": {
required:true,
minlength:5,
maxlength:15
}
}
or
rules["jform[name]"] = {...};
Upvotes: 1