2012-08-29 80 views
3

我需要在表單中顯示錯誤。我該如何處理看起來像這樣的對象

錯誤可以追加到輸入名稱表單中,以防在兒童中定義的錯誤,這是常見的情況(1)。

但可能發生的錯誤是在json對象(2)的根節點中定義的。
在這種情況下,它應該被附加到formElement。

以下代碼(3)適用於案例(1),但不適用於案例(2)。

我應該如何修改它以使它在兩種情況下都能正常工作?
P.S .:我使用下劃線和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."] 
     } 
    } 
}); 
+0

根級別中的'name'是什麼? – Bergi

回答

0

您應該開始頂級遞歸:

var xhr = JSON.parse("…"); 

(function recurse(obj, name) { 
    if (obj.errors) { 
     var inputElement = element.find('[name="' + name + '"]'); 
     inputElement.closest('.control-group').addClass('error'); 
     parserError(obj.errors, inputElement); 
    } 
    if ("children" in obj) 
     for (var prop in obj.children) 
      recurse(obj.children[prop], prop); 
})(xhr, "top"); 
相關問題