Input field validation for Email

时间:2017-08-04 12:23:41

标签: html angularjs validation

I have the following HTML code. The validation takes place as soon as I start typing, i.e. as long as the string is not a valid email adddress, the error message is displayed. However, I want it to be displayed once the input field is out of focus and I go on to another input field for example. Is that possible even?

<div>
  <label>Mail</label><br>
  <input type="email" name="email" placeholder="Mail Address"
     ng-model="emailAddress" required>
  <span style="color:red;font-family:Open Sans;font-weight: 400;font-size: 14px" ng-show="form.email.$dirty && form.email.$invalid"></span>
  <span ng-show="form.email.$error.required">Email is required.</span>
  <span ng-show="form.email.$error.email">Invalid email address.</span>                
</div>

2 个答案:

答案 0 :(得分:1)

You can use $touched.

<div>
  <label>Mail</label><br>
  <input type="email" name="email" placeholder="Mail Address"
     ng-model="emailAddress" required>
  <span style="color:red;font-family:Open Sans;font-weight: 400;font-size: 14px" ng-show="form.email.$dirty && form.email.$invalid"></span>
  <span ng-show="form.email.$error.required && form.email.$touched">Email is required.</span>
  <span ng-show="form.email.$error.email && form.email.$touched">Invalid email address.</span>                
</div>

答案 1 :(得分:0)

The Angular 1.3 introduced the $touched property. When you touch and leave the input (input lost the focus) the $touched value switch to true.

@property {boolean} $untouched True if control has not lost focus yet.

@property {boolean} $touched True if control has lost focus.

@property {boolean} $pristine True if user has not interacted with the control yet.

@property {boolean} $dirty True if user has already interacted with the control.

<div>
  <label>Mail</label><br>
  <input type="email" name="email" placeholder="Mail Address"
     ng-model="emailAddress" required>
  <span style="color:red;font-family:Open Sans;font-weight: 400;font-size: 14px" ng-show="form.email.$dirty && form.email.$invalid"></span>
  <span ng-show="form.email.$error.required && form.email.$touched">Email is required.</span>
  <span ng-show="form.email.$error.email && form.email.$touched">Invalid email address.</span>    
</div>