Ray Ray - 24 days ago 13
jQuery Question

jquery validate show error on dynamic field name

I'm using the jquery validate plugin to validate my form. There is also server side validation and I'd like to be able to flag up the fields showing errors from the server side validation such as unique email if it's not been caught by the jquery validation.

I'm receiving a json object from my server script which has field name and then error.

I thought of using the

showErrors()
function but can't work out the right way to get this to work. Here's my script so far:

$.each(errors, function (key, value) {
console.log("Key:", key);
validator.showErrors({
key: value[0]
})
});


This throws an error -
uncaught typeError
so I assume referencing key as the field name doesn't cut it. I realise it's evaluating
key
as the field name rather than the value contained in
key
which is what I'm trying to achieve.

Thanks

Answer

You're looping through a JSON object. I will assume that your errors json object it is something like this:

var errors = [
  {"firstname": "I know that your firstname is Ray, Ray!"},
  {"age":"You're not so old"},
  {"job":"You're not Buddha"}
];

At the first iteration of your $.each loop the v parameter it's the whole object at k position, in this case:

{"firstname": "I know that your firstname is Pete, Pete!"}

You can see that here is needed a second $.each loop that will iterates over the properties on each object element.

$.each(errors, function() {
  $.each(this, function(k, v) {
    /* ... code ... */
  });
});

From documentation showErrors methods take an Object as a parameter. You need to build it.

//my validator object
var validator = $( "#yourFormID" ).validate();

// empty object that I'll fill with name input/errors
var objErrors = {};

//iterate over array of objects/maps
$.each(errors, function() {
  //iterate over the properties on each object
  $.each(this, function(k, v) {
    objErrors[k] = v;
  });
});
validator.showErrors(objErrors);

In the loops I've built my object that I've passed to the method showErrors of the object validator. I choose this solution because like so, I call only one time showErrors instead of calling it everytime in the $.each loop.

Here a working jsbin example.