Javascript – Use of square brackets in objects

bracketsjavascript

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.

Best Solution

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:

The basics

{} 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();

properties can be accessed via . and [] notation:

//these are the same
a.b = c;
a['b'] = c;

Object literals can be set using literal values or strings:

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
};