I need to display the error in a form.
The error can be appended to the input-name form, in case of error defined in children, which is the common case (1).
But could happen that the error is defined in the root node of the json object (2).
In this case it should be appended to the formElement.
The following code (3) works for the case (1) but not for the case (2).
How should I modify it in order to make it working in both cases?
P.S.: I am using underscore and jquery.
(1)
var xhrObj_1 = JSON.parse('{ "children":{"points":{"errors":["This value should not be blank."]},"message":[],"recipient_id":{"errors":["This value should not be blank."]}}}');
(2)
var xhrObj_2 = JSON.parse('{ "errors":["This form should not be …."], "children":{"points":{"errors":["This value should not be blank."]},"message":[],"recipient_id":{"errors":["This value should not be blank."]}}}');
(3)
var parser = function (object) {
_.each(object, function (xhrObject, name) {
console.log(xhrObject)
if (xhrObject.errors) {
var inputElement = element.find('[name="' + name + '"]');
inputElement.closest('.control-group')
.addClass('error');
parserError(xhrObject.errors, inputElement);
} else {
parser(xhrObject); // it is ok for xhrObj_1
// it fails for xhrObj_2
}
});
};
// example with xhrObj_2 which does not work
parser({
"errors": ["errro1"],
"children": {
"points": {
"errors": ["This value should not be blank."]
},
"message": [],
"recipient_id": {
"errors": ["This value should not be blank."]
}
}
});