2016-12-02 75 views
1

我是AngularJS中的新成員。我想爲輸入設置驗證,如最小長度爲5,最大長度爲6.AngularJS ng-minlength ng-required not working

我必須設置5到6僅數字到我的文本框中。

對於這個我使用下面的代碼,但它不工作

<div class="input-wrap lg-input"> 
    <input type="text" name="num" class="form-input" placeholder="Enter 5-6 digits" ng-minlength="5" maxlength="6" 
     ng-model="profInfo.Number" ng-required="true"> 
    <div class="error" ng-show="profInfoForm.$submitted || profInfoForm.num.$touched"> 
     <span ng-show="profInfoForm.num.$error.required">Required Field</span> 
     <span ng-show="profInfoForm.num.$error.minlength">Invalid input</span> 
    </div> 
</div> 
<div class="button-ctr"> 
    <button class="button" ng-class="profInfoForm.$valid ? 'active' : 'disable'">Next</button> 
</div> 

目前這一工作象下面這樣:

當文本框是空的,我點擊下一步按鈕,它顯示必填字段錯誤消息是正確的。

我輸入的數字不能超過6位。

當我在文本框中輸入1位數字並點擊按鈕時,它顯示錯誤的必填字段錯誤消息。

當我鍵入第5位數字時,顯示錯誤的無效輸入錯誤消息。

我正在使用AngularJS v1.5.5。

+0

你能解釋「它不工作」的一部分?你期望什麼,以及它如何表現? –

+0

爲什麼使用maxlength來支持ng-maxlength? – DevDig

+0

@DevDig我希望該用戶不能輸入大於6位數的輸入。 – user3441151

回答

0

變化ng-show="profInfoForm.$submitted || profInfoForm.num.$touched"ng-show="(profInfoForm.num.$dirty || submitted)"

<input type="text" name="num" class="form-input" placeholder="Enter 5-6 digits" minlength="5" maxlength="6" ng-model="profInfo.Number" ng-required="true"> 
    <div class="error" ng-show="(profInfoForm.num.$dirty || submitted)"> 
     <span ng-show="profInfoForm.num.$error.required">Required Field</span> 
     <span ng-show="profInfoForm.num.$error.minlength">Invalid input</span> 
    </div> 
    </div> 

看一看demo

+0

它不工作。 – user3441151

+0

演示工作。 –

+0

@ user3441151什麼不適用於演示? –

0

1)嘗試這個 -

<input type="text" name="num" class="form-input" placeholder="Enter 5-6 digits" ng-minlength="5" ng-maxlength="6" ng-model="profInfo.Number" required> 
    <div class="error" role="alert"> 
     <span ng-show="profInfoForm.num.$error.required">Required Field</span> 
     <span ng-show="profInfoForm.num.$error.minlength">Too Short!</span> 
     <span ng-show="profInfoForm.num.$error.maxlength">Too Long!</span> 
    </div> 

2)但我會喜歡這個下面的解決方案用於角度形式驗證。

<form role="form" name="FORMNAME" ng-submit="vm.submitForm(formData)" novalidate>   
    <div class="form-group form-md-line-input" ng-class="{ 'has-error' : FORMNAME.num.$invalid && !FORMNAME.num.$pristine}"> 
    <label class="col-md-3 control-label">Number <span style="color:red;">*</span></label> 
    <div class="col-md-8"> 
     <input type="text" class="form-control" name="num" ng-model="formData.number" placeholder="Enter 5-6 digits" ng-minlength="5" ng-maxlength="6" required> 
     <span class="help-block" ng-show="FORMNAME.num.$error.required">Please enter name</span> 
     <span class="help-block" ng-show="FORMNAME.num.$error.minlength">Too Short!</span> 
     <span class="help-block" ng-show="FORMNAME.num.$error.maxlength">Too Long!</span> 
    </div> 
    </div> 
</form> 

使用自舉「有錯誤」級以及與此,如果任何驗證失敗,「有錯誤」類的工作與對照標籤,表單控件類的元素會變成紅色。

「novalidate」會阻止chrome html5驗證。