Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validator, programmatically show errors

I can do something like this:

validator.showErrors({ "nameOfField" : "ErrorMessage" });

And that works fine, however if I try and do something like this:

var propertyName = "nameOfField";
var errorMessage = "ErrorMessage";
validator.showErrors({ propertyName : errorMessage });

It throws an 'element is undefined' error.

like image 282
ChadT Avatar asked Mar 02 '23 00:03

ChadT


2 Answers

What about:

var propertyName = "nameOfField";
var errorMessage = "ErrorMessage";

var obj = new Object();
obj[propertyName] = errorMessage;

validator.showErrors(obj);

Is worth to notice that the following three syntaxes are equivalent:

var a = {'a':0, 'b':1, 'c':2};

var b = new Object();
b['a'] = 0;
b['b'] = 1;
b['c'] = 2;

var c = new Object();
c.a = 0;
c.b = 1;
c.c = 2;
like image 150
Christian C. Salvadó Avatar answered Mar 12 '23 11:03

Christian C. Salvadó


The reason you're getting an 'element is undefined' error there by the way, is because:

var propertyName = "test";
var a = {propertyName: "test"};

is equivalent to..

var a = {"propertyName": "test"};

i.e., you're not assigning the value of propertyName as the key, you're assigning propertyName as a string to it.

like image 38
Sciolist Avatar answered Mar 12 '23 11:03

Sciolist