2014-08-27 151 views
2

Iam試圖通過單擊名爲'next'的按鈕逐步驗證我的表單。 有沒有辦法觸發自定義事件觸發部分表單驗證? 類似的東西:如何觸發自定義事件以觸發部分表單驗證?

<input type="text" id="age-id" name="age" 
    ng-model-options="{updateOn: 'ValidateStepOne'}" 
    min="18" 
    max="99" 
    ng-model="data.age" 
> 

在按鈕的onclick觸發事件:

$scope.validate = function() { 
    $rootScope.$broadcast('ValidateStepOne'); 
}; 

任何幫助,將好心讚賞。 親切的問候

OliverKK

+0

更多的代碼將有助於更多地理解佈局。但是如果你有你的UI設置,我想你可以讓每一步都是自己的形式,所以按鈕提交會導致該步驟的表單驗證。 – fiskers7 2014-08-27 14:49:08

+0

感謝您的回覆。這些步驟的驗證是在發佈公式之前進行預驗證。將表單分成子表單不是一種選擇。 – OliverKK 2014-08-27 14:55:13

回答

1

我把巨大的表單分成了子表單(感謝@ fiskers7),這非常方便。 驗證通過使用custom trigger單擊 next按鈕來驗證當前步驟。 當自定義提交事件被觸發時,將會執行驗證器和其他使用的驗證器。

<form id="form1" ng-submit="validate(1)" ng-model-options="{ updateOn: 'submit' }" novalidate> 
     <input type="text" ng-model="name" required> 
     <span ng-show="form1.$submitted && form1['name'].$error.required">Name is required!</span> 
     <input type="submit" value="next"> 
    </form> 

    <form id="form2" ng-submit="validate(2)" ng-model-options="{ updateOn: 'submit' }" novalidate> 
     <input type="text" ng-model="surename" required> 
     <span ng-show="form2.$submitted && form1['surename'].$error.required">Name is required!</span> 
     <input type="submit" value="next"> 
    </form> 

控制器內的驗證功能submit看起來是這樣的:

$scope.validate = function(num) { 
    $scope['form' + num].$setSubmitted(true); 
    if (!$scope['form' + num].$valid) { 
     $scope.scrollToTop(); 
    } else if (num < $scope.maxSteps) { 
     $scope.next(num + 1); 
    } else { 
     $scope.submit(); 
    } 
    } 

詳情請參見該AngularJS文檔: https://docs.angularjs.org/guide/forms

親切的問候

OliverKK

0

您可以將表格分成幾塊使用ng-if來決定是否顯示它們。

<form action="" name="myForm"> 
    <div ng-if="step == 1"> 
     <input type="text" required="true" name="input1" ng-model="inputVal1"/> 
    </div> 
    <div ng-if="step == 2"> 
     <input type="text" required="true" name="input2" ng-model="inputVal2"/> 
    </div>    
</form> 

參見example

+1

謝謝你的答覆。一開始,我的想法就像你的建議。但事實證明,以較小的形式分開巨大的形式會更好。這樣做的關鍵在於,每個表單都有自己的提交按鈕,這使得驗證非常簡單。 – OliverKK 2014-09-19 09:37:52