我在使用Angular.js进行表单验证时遇到了问题。
这是我的HTML代码:
<form class="form-horizontal" name="regForm" novalidate>
<div class="form-group" ng-class="{'has-error':regForm.name.$touched && regForm.name.$invalid}">
<label class="control-label col-sm-2">Username:</label>
<div class="col-sm-10">
<input class="form-control" type="text" name="name" ng-model="name" placeholder="Enter Username" ng-minlength="5" ng-maxlength="10" required>
</div>
<div class="help-block" ng-messages="regForm.name.$error" ng-if="regForm.name.$touched">
<p ng-message="minlength">Your name is too short.</p>
<p ng-message="maxlength">Your name is too long.</p>
<p ng-message="required">Your name is required.</p>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Password:</label>
<div class="col-sm-10">
<input class="form-control" type="password" name="pwd" ng-model="pwd" placeholder="Enter Password" ng-pattern="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$" maxlength="12" >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Repeat Password:</label>
<div class="col-sm-10">
<input class="form-control col-sm-6" type="password" name="num" ng-model="repeat password" placeholder="Repeat password">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Email Address:</label>
<div class="col-xs-10">
<input class="form-control col-sm-6" type="email" name="num" ng-model="email" placeholder="Enter Email Address">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Repeat Email Address:</label>
<div class="col-xs-10">
<input class="form-control col-sm-6" type="email" name="num" ng-model="repeatemail" placeholder="Repeat Email Address">
</div>
</div>
</form>
对于第一个输入字段(即用户名),我尝试使用ng-messages和has-error进行验证。这是我得到的输出
我需要具体的输出,如果名字很小意味着我必须收到错误消息,例如&#34;你的名字太小&#34;。但是当我输入名称时,我一次收到三条错误消息。
答案 0 :(得分:0)
您需要为每条要显示的消息指定条件:
<p ng-if="regForm.name.$error.minlength">Your name is too short.</p>
答案 1 :(得分:0)
您的代码对我有用。我怀疑你没有包含angular-messages
模块。从角度文档:
首先,获取文件:
Google CDN,例如
//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-messages.js
NPM,例如
npm install angular-messages@X.Y.Z
Bower,例如
bower install angular-messages#X.Y.Z
然后,在HTML中包含angular-messages.js:
<script src="path/to/angular.js"></script>
<script src="path/to/angular-messages.js"></script>
最后,加载模块 在您的应用程序中,将其添加为依赖模块:
angular.module('app', ['ngMessages']);
有了这个你已经准备好开始了!