问题
I'm doing validation in AngularJS, and I have a div that is displayed if there are 3 types of errors.
For required I want to show the error message only if the page is submitted with empty value
<div class="error" data-ng-show="submitted && mainForm.email.$error.required" />
For the regex validation I want it to flag real-time, default behavior.
<div class="error" data-ng-show="mainForm.email.$error.pattern" />
The problem I'm facing is with minlength. I don't want to show it while they are typing. It's annoying because they haven't finished typing. I don't want to display it on submit either, I think that's too late. I'd like to show it when they are no longer in focus of the element.
If //mainForm.email.$focus existed I could simply do this
<div class="error" data-ng-show="mainForm.email.$error.minlength &&
!mainForm.email.$focus"/>
Anyone know of any way to do this kind of check or any non drawn out alternative?
Thanks!
回答1:
Yes it does
you can use ngFocus and ngBlur for this purpose
here is the code
<form name="mainForm">
<span ng-show="mainForm.email.$error.pattern && !focus">error here</span>
<input name="email" ng-pattern="..." ng-focus="focus=true" ng-blur="focus=false" type="text" />
</form>
ngFocus and ngBlur take expression and ngShow shows upon true evaluation
回答2:
You need to read about ModelOptions, debounce and updateOn can delay model change trigger event or trigger change on DOM event https://docs.angularjs.org/api/ng/directive/ngModelOptions
Check the example on the page
<div ng-controller="ExampleController">
<form name="userForm">
Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ updateOn: 'blur' }"
ng-keyup="cancel($event)" /><br />
Other data:
<input type="text" ng-model="user.data" /><br />
</form>
<pre>user.name = <span ng-bind="user.name"></span></pre>
</div>
回答3:
Another simple option is:
<input type="text"
name="searchText"
ng-model="searchText"
ng-blur="searchIsInActive()"
ng-click="searchIsActive()"
placeholder="Search">
来源:https://stackoverflow.com/questions/25109047/determine-whether-form-input-has-focus