Determine whether form input has focus

Proximo picture Proximo · Aug 3, 2014 · Viewed 36.6k times · Source

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!

Answer

Ravi Sahu picture Ravi Sahu · Jan 3, 2015

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