2014-09-29 55 views
1

我試圖做一個表單驗證,其中包含一個名爲「description」的字段。在該 1.description字段不能爲空 2.description字段不能少於5個字符 3.描述字段不能超過60個字符。angularjs驗證問題的形式

對於驗證我已經完成,如果我輸入3字符的描述中,示出了既用於字段爲空,並且字段中的錯誤消息具有小於5個字符。

這樣的(超過字符的限制時發生同樣的情況)

enter image description here

我怎麼能顯示正確的錯誤消息,當出現這種情況?當字符限制小於5或大於60時,我只想顯示「描述太短/太長」。並且當沒有描述被包括時,「需要描述」錯誤信息。

這是我做了什麼

<!-- DESCRIPTION --> 
     <div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && userForm.username.$dirty && submitted || userForm.username.$invalid && userForm.username.$pristine && submitted }"> 
      <label>Description</label> 
      <input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="5" ng-maxlength="60" required> 
      <label><p ng-show="userForm.username.$invalid && userForm.username.$dirty && submitted || (userForm.username.$invalid && userForm.username.$pristine) && submitted " class="help-block "><font color="#009ACD">Description is required.</font></p></label> 
      <label><font color="white"><p ng-show="userForm.username.$error.minlength && submitted" class="help-block"><font color="#009ACD">Description is too short.</font></p></label> 
      <label><p ng-show="userForm.username.$error.maxlength && submitted" class="help-block"><font color="#009ACD">Description is too long.</font></p></label> 
     </div> 



      <div class="col"style="text-align: center"> 
      <button align="left"class="button button-block button-reset" type="reset" value="Reset" style="display: inline-block;width:100px;text-align:center " 
      ng-click="submitted=false" padding-top="true">Reset</button> 


      <button class="button button-block button-positive" style="display: inline-block;width:100px " 
      ng-click="submitted=true" type="submit" padding-top="true">Submit</button> 
      </div> 

回答

1

你總是看到,因爲你是依靠userForm.username.$invalid財產,這將始終是真實的,如果任何驗證失敗「描述是必需的」消息。

相反,您應該將其更改爲與其他類似,並使用userForm.username.$error.required鍵。

所以,你的第一個標籤就變成了:

<label><p ng-show="userForm.username.$error.required && userForm.username.$dirty && submitted || (userForm.username.$error.required && userForm.username.$pristine) && submitted" class="help-block "><font color="#009ACD">Description is required.</font></p></label> 
+0

我早點試過這種方法。但是當我使用該字段時,即使該字段爲空,錯誤消息也會顯示爲「描述太短」 – CraZyDroiD 2014-09-29 09:36:52

+0

感謝它的工作! – CraZyDroiD 2014-09-29 10:31:43

1

用在你的NG-節目表達 「說明需要」 看起來我錯了。 嘗試將其簡化爲:

ng-show="submitted && userForm.username.$error.required" 
+0

謝謝你的工作。謝謝你爲了簡化它 – CraZyDroiD 2014-09-29 10:32:09