Since the rules that the user sees should be the same rules that the server uses, I want to store validation rules in a JSON file and load them for both cases.
However, the jQuery validation plugin seems to use settings that are not valid JSON, such as
$('form').validate( {
rules : {
userid : {
required : true,
maxlength : 20
}
}
});
Note how none of the keys or string values are double quoted. This makes my server-side JSON parser sad. What can I do so that I only have to maintain one set of rules?
My idea is that when the request is actually sent to the server, my server (Java servlet in my case) will open the json file that has the rules variable and parse it, so that it knows what logic to apply to the posted parameters, and whether to accept or reject them.
However, the JSON specs do not allow for unquoted keys and values like javascript arrays do, so I can’t store the rules as they would normally be for just jQuery use.
While JavaScript literals are not always valid JSON, JSON is always a valid JavaScript expression. You can use it: