如何区分表单中的验证并分别显示与每个验证相关的错误消息?

时间:2017-11-14 10:03:36

标签: angularjs twitter-bootstrap-4

这就是我做的......

<form name="userForm" ng-submit="submitForm()" novalidate>
<!-- NAME -->
<div ng-class="{'has-error' : userForm.name.$invalid && !userForm.name.$pristine }">

  <label>Name</label>

  <input type="text" name="name" class="form-control" id = "focusedInput" ng-model="user.name" required>
  <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">Your name is required.</p>
</div>

<!-- USERNAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$pristine }">
    <label>Username</label>
    <input type="text" name="username" class="form-control" ng-model="user.username" required id = "focusedInput" ng-minlength="3" ng-maxlength="8">
    <p ng-show="userForm.username.$error.minlength" class="help-block">Username is too short.</p>
    <p ng-show="userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
  <p ng-show="userForm.username.$invalid && !userForm.username.$pristine" class="help-block">Your Username is required.</p>

</div>

 <button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Submit</button>

</form>

我尝试对用户名字段使用类似的验证,当它保留为空时,就像我为名字字段所做的那样。但问题是:与名称和用户名相关的错误消息都是在用户名字段的最小长度条件的开始处打印的。任何人都可以帮我这个吗?

1 个答案:

答案 0 :(得分:1)

将$ dirty支票添加到您的ng-show。当用户操纵表单时,De $ dirty标志为真。

<p ng-show="userForm.username.$error.minlength && userForm.username.$dirty" class="help-block">Username is too short.</p>