javascript Angular JS - 当文本字段失去焦点时显示验证错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21280962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular JS - Display validation errors when textfield lose focus
提问by Vinodh
I want to perform validation on input field , when user lefts the field .
当用户离开该字段时,我想对输入字段执行验证。
My.html
我的.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>
I want to display invalid-message div and span , corresponding to error in email field . Now the code works fine .
我想显示 invalid-message div 和 span ,对应于 email field 中的错误。现在代码工作正常。
But my requirement is to show invalid-message div and span when user finished typing in email.How to perform this your comments are welcome
但我的要求是在用户完成输入电子邮件时显示无效消息 div 和 span。如何执行此操作,欢迎您提出意见
Please find the fiddle here Validation Demo fiddle
请在这里找到小提琴验证演示小提琴
回答by Davin Tryon
You can accomplish this by setting a temporary variable that indicates whether the user has left the field. Best place to do this is in the ng-blur
directive (so, you can keep all of this on the view).
您可以通过设置一个指示用户是否已离开该字段的临时变量来完成此操作。执行此操作的最佳位置是在ng-blur
指令中(因此,您可以将所有这些都保留在视图中)。
Here is an 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>
You can see the introduction of EmailVisited
that is set on ng-blur
.
你可以看到EmailVisited
设置上的介绍ng-blur
。
回答by Robert Ravikumar
try using form.userEmail.$touched
尝试使用 form.userEmail.$touched