2

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That's great. I'll have a go at implementing tonight. Thank you for a through answer. Really useful. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.