エラーをフォームに表示する必要があります。
子で定義されたエラーの場合、エラーは入力名フォームに追加できます。これは一般的なケースです(1)。
ただし、エラーがjsonオブジェクトのルートノードで定義されている可能性があります(2)。
この場合、formElementに追加する必要があります。
次のコード(3)は、ケース(1)では機能しますが、ケース(2)では機能しません。
両方の場合に機能させるには、どのように変更する必要がありますか?
PS:私はアンダースコアと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."]
}
}
});