我想在用户离开该字段时对输入字段执行验证。
My.html
<div ng-form="form" novalidate>
<input type="email" name="userEmail" class="form-control username"
ng-model="login.username" placeholder="Email" required />
<input type="password" name="password" class="form-control password" placeholder="Password" ng-model="login.password" required />
<div class="invalid-message" ng-show="form.userEmail.$dirty && form.userEmail.$invalid">
<span class="invalid-mail" ng-show="form.userEmail.$error.required">Invalid:Tell us
your email.</span>
<span class="invalid-mail" ng-show="form.userEmail.$error.email">Invalid:This is not a valid email.</span>
</div>
</div>
我想显示无效消息 div 和 span ,对应于电子邮件字段中的错误。 现在代码工作正常。
但我的要求是在用户完成输入电子邮件时显示无效消息 div 和 span。如何执行此操作欢迎您提出意见
请在这里找到 fiddle Validation Demo fiddle
最佳答案
您可以通过设置一个指示用户是否离开该字段的临时变量来完成此操作。执行此操作的最佳位置是在 ng-blur
指令中(因此,您可以将所有这些保留在 View 中)。
这是一个 updated fiddle.
<form name="form" novalidate>
<input type="email" ng-blur="visitedEmail = true" name="userEmail" class="form-control username" ng-model="username" placeholder="Email" required />
<input type="password" ng-blur="visitedPassword = true" name="password" class="form-control password" placeholder="Password" ng-model="password" required />
<div ng-show="form.userEmail.$dirty && form.userEmail.$invalid && visitedEmail">
<span ng-show="form.userEmail.$error.required">Invalid:Tell us your email.</span>
<span ng-show="form.userEmail.$error.email">Invalid:This is not a valid email.</span>
</div>
</form>
可以看到在ng-blur
上设置了EmailVisited
的介绍
关于javascript - Angular JS - 当文本字段失去焦点时显示验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21280962/