2014-10-27 29 views
0

我需要:我需要添加額外的驗證輸入,通過添加屬性到這個輸入。如何在角度上正確添加額外的驗證指令?

首先,我plnkr例子是here

我已經嘗試過什麼?:我加了指令,所以當我添加屬性輸入,輸入的數值是由正則表達式^5$驗證。另外,我添加了輸入需求。我現在正在談論第二個輸入(輸入的名稱是input2)。

所以,我添加了屬性「my-attribute」和「required」。當輸入中沒有任何內容時,我期待myForm.item[1].$error中的兩個項目:它可以 - 有屬性myAttributerequired。現在,我會添加一些到input2,例如「abc」,現在我預計myForm.item[1].$error只有myAttribute屬性(因爲需要驗證通過,但myAttribute驗證不是),但myForm.item[1].$error中有屬性myAttributeparse。什麼是parse屬性?爲什麼要加入$error

我應該注意到,當我將5輸入到輸入2時myForm.item[1].$error爲空,因爲傳遞了require和myAttribute驗證(並且此行爲是預期的)。

現在,當我清除input2時,還有屬性parsemyAttribute。爲什麼?當字段input2爲空時,我期望requiredmyAttributemyForm.item[1].$error中,但是沒有。

那麼,爲什麼我得到奇怪的屬性parse$error以及如何讓我的例子工作?

表單示例代碼創建here並通過指令驗證輸入的方法建立在答覆this post

回答

2

What is parse property? Why it is adding to $error?

parse屬性當解析器之一返回undefined自動由角添加。 從Angular documentation

Returning undefined from a parser means a parse error occurred. No $validators will run and the 'ngModel' will not be updated until the parse error is resolved. The parse error is stored in 'ngModel.$error.parse'.

不知道如果我在這裏缺少一些用例,但是從解析器改變return條款應該足夠:

//For DOM -> model validation 
ngModel.$parsers.unshift(function(value) { 
    var valid = new RegExp("^5$").test(value); 
    ngModel.$setValidity('myAttribute', valid); 
    return value; 
}); 
+0

好有關解析。但是,有必要的屬性,我需要首先與需要的工作。當表單爲空時,必須有兩個屬性出錯:required和myAttribute,對不對?爲什麼不?兩個驗證都沒有通過。關於解析,確定關於myAttribute,但需要什麼? – 2014-10-27 19:48:16

+0

*「當表單爲空時,必須有兩個屬性出錯:required和myAttribute,對嗎?」*是的,這就是我所得到的。你不是看到一樣嗎?這不是預期的行爲? – bmleite 2014-10-27 20:11:04

+0

不,當表格爲空白時(不是首先加載,但輸入了一些東西並清除輸入後)我看不到相同的 – 2014-10-27 21:11:50