2016-08-16 77 views
0

用一個簡單的形式:角1.5表單驗證 - 如何驗證多個輸入都是空或滿

<form name="simpleForm"> 
    <input ng-model= "profile.cat" name="cat"> 
    <input ng-model= "profile.dog" name="dog"> 
    <input ng-model= "profile.mouse" name="mouse"> 

</form> 

什麼是驗證所有三個輸入已經被填充或空的最簡單的方法?換句話說,只有當所有三個輸入都被填充或者所有三個輸入都爲空時,表格纔有效。我在一個自定義的驗證多次嘗試,一直以來把一個僞指令中的一個或多個的三個輸入的線路,如:

<input ng-model= "profile.cat" name="cat" all-empty-all-full > 

自定義的驗證:

function allEmptyAllFull() { 
    return { 
    restrict: 'A', 
    require: 'ngModel', 
    link: function (scope, element, attrs, ngModel) { 
     // nothing I put in here does the job! 
    } 
    } 
} 
angular 
    .module('app') 
    .directive('allEmptyAllFull', allEmptyAllFull); 

我已經嘗試在鏈接函數中放入一個ngModel。$ validators.allEmptyAllFull函數,但在裏面我無法訪問其他兩個輸入。我已經看到了其他代碼,其中人們在「比較」表單輸入中放入了一個自定義屬性,但在這種情況下,這並沒有讓我獲得任何地方。任何幫助非常感謝。

編輯:我最初的問題措辭不佳,對不起。我不希望任何輸入是獨立需要的,但如果有人向其中的任何一個輸入文本,則需要完成其他兩個輸入。全部或沒有。

+0

您可以檢查控制器。看到這個http://stackoverflow.com/questions/20054055/angularjs-check-if-form-is-valid-in-controller –

回答

0

爲了使提交的所有三個輸入的補釦,你可以做這樣的事情。

<form name="simpleForm"> 
    <input ng-model= "profile.cat" name="cat" ng-required="simpleForm.dog.length > 0 || simpleForm.mouse.length > 0"> 
    <input ng-model= "profile.dog" name="dog" ng-required="simpleForm.cat.length > 0 || simpleForm.mouse.length > 0"> 
    <input ng-model= "profile.mouse" name="mouse" ng-required="simpleForm.cat.length > 0 || simpleForm.dog.length > 0"> 

    <button>Action</button> 
</form> 

只有當所有三個輸入都具有某個值時,動作按鈕纔會啓用。

+0

我也希望能夠提交所有三個空的表格! – TDB

+0

所以你說,如果我沒有在第一個文本框中輸入任何內容,而其他兩個都是空的,那麼表單是有效的。但是如果我輸入任何文本框,現在也需要其他兩個文本框。 –

+0

是的,確切地說。我一直在努力工作一段時間,沒有牽引。主要的問題是訪問其他兩個輸入的值,而在一個自定義的驗證器指令附加到我輸入的輸入。我可以想出其他解決方案,以防止直接從控制器提交表單(只需投入條件我的提交功能),但我想要一個更清潔的解決方案,使用ngModel。$ validators或$ setValidity。 – TDB

1

在必填字段中使用內置的必需指令。

<form name="simpleForm"> 
    <input ng-model= "profile.cat" name="cat" required> 
    <input ng-model= "profile.dog" name="dog" required> 
    <input ng-model= "profile.mouse" name="mouse" required> 
</form> 

,您可以檢查的形式是有效

<button ng-disabled="simpleForm.$invalid">Action</button> 
+0

我需要比這更復雜的東西。我希望能夠提交所有三個輸入全部或全部三個輸入空的表單 - 只是沒有任何介於兩者之間的任何東西。 – TDB

+0

@TDB,爲什麼不用'ng-disabled =「ctrl.isFormValid()」'用控制器中的函數? –