我试图对包含名为" description"的字段的表单进行验证。 。在那里面 1.description字段不能为空 2.description字段不能少于5个字符 3.description字段不能超过60个字符。
对于我已经完成的验证,如果我输入3个字符描述,则显示该字段为空且字段少于5个字符的错误消息。(超出字符限制时也是如此)
喜欢这个
当发生这种情况时,如何显示正确的错误消息?我只想显示"描述太短/太长"当字符限制小于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>
答案 0 :(得分: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>
答案 1 :(得分:1)
@CrazyDroid你可以查看这个链接,在你的表格上进行验证,这完全符合你的要求。
http://scotch.io/tutorials/javascript/angularjs-form-validation
答案 2 :(得分:1)
您的ng-show表达式使用&#34; 说明是必需的&#34;看起来不对我。 尝试将其简化为:
ng-show="submitted && userForm.username.$error.required"