I have some JavaScript that works with jQuery.validate. This takes a JSON object that comes back from the server, and passes it to the showErrors
function. The response.errors
object looks like this...
{[
{ item1: "Email", item2: "Invalid format" },
{ item1: "ExpiryDate", item2: "Must be in the future" }
]{
The following ES6 code works fine...
for(var i = 0; i < response.errors.length; i++) {
$('form').validate()
.showErrors({ [response.errors[i].item1]: response.errors[i].item2 });
}
However, I've just discovered that IE doesn't support ES6, so this doesn't work there. I tried using es6-shim (and es-5shim), but it didn't help.
I've been trying to write some ES5-compatible code to do the same thing, but have failed at every attempt. I have looked at answers such as this one and this one, but I just can't get anything to work.
My latest attempt was the following...
var error = {};
error[response.errors[i].item1] = response.errors[i].item2;
$('form').validate().showErrors(error);
However, despite the fact that dumping error
and the previous code to the console showed them to be identical, when I try to use this code, I get an error in the console...
Uncaught (in promise) TypeError: Cannot read property 'type' of undefined at $.validator.highlight (jquery.validate.js:344) at $.validator.defaultShowErrors (jquery.validate.js:912) at $.validator.showErrors (jquery.validate.js:546) at handleServerResponse (Donate:305)
The line in question is the one where I call showErrors
Anyone able to help me?
Update just to clarify, the reason I'm doing this in a loop is that the server-side code returns three types of errors, normal ones related to a specific input element, general ones relating to the data as a whole, and ones specific to a payment section of the form. I only pass the first type to jQuery.validate
, as the second type are displayed in an independent part of the form, and the third type have to be handled differently as the payment processor generates its own HTML in an iframe
, meaning I have to add the error manually.
Second update Turns out that it was some code on a separate part of the page that was throwing out my JavaScript. The code I had, and that shown in the two answers was fine, it was a separate problem.
To build the object you can use a loop through the array you receive from the AJAX request, then by using bracket notation to add properties to the object, you can pass it to showErrors()
, something like this:
var errors = {};
response.errors.forEach(function(err) {
errors[err.item1] = err.item2
});
$('form').validate().showErrors(errors);