Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate the input field on blur with Angular

I made a simple testing input fields, But I trying to convert the validation on blur, But i don't have any idea to achive this, since I am not such familiar with angularjs.

any one help me to validate only one blur in this example please..

myJs:

angular.module('myApp', [])
.controller('FormController', function($scope) {
  $scope.fields = [
    {placeholder: 'Username', isRequired: true},
    {placeholder: 'Password', isRequired: true},
    {placeholder: 'Email (optional)', isRequired: false}
  ];

  $scope.submitForm = function() {
    alert("it works!");
  };
});

html:

<div ng-app="myApp">
<form name="signup_form" ng-controller="FormController" ng-submit="submitForm()" novalidate>
  <div ng-repeat="field in fields" ng-form="signup_form_input">
    <input type="text"
           name="dynamic_input"
           ng-required="field.isRequired"
           ng-model="field.name"
           placeholder="{{field.placeholder}}" />
    <div ng-show="signup_form_input.dynamic_input.$dirty && signup_form_input.dynamic_input.$invalid">
      <span class="error" ng-show="signup_form_input.dynamic_input.$error.required">The field is required.</span>
    </div>
  </div>
  <button type="submit" ng-disabled="signup_form.$invalid">Submit All</button>
</form>
</div>

Live Demo

like image 656
3gwebtrain Avatar asked Aug 07 '14 09:08

3gwebtrain


2 Answers

If you update to Angular 1.3 you can use ng-model-options to update the model on blur.

<input type="text"
       name="dynamic_input"
       ng-required="field.isRequired"
       ng-model="field.name"
       ng-model-options="{ updateOn: 'blur' }"
       placeholder="{{field.placeholder}}" />

fiddle

However, if you can't update then there are plenty of ways to do this here.

like image 76
Ben Fortune Avatar answered Sep 28 '22 06:09

Ben Fortune


If you have a custom validation, a simple way to go is using ngBlur. Add the following to your field and write a validation function in your controller:

<input type="text"
       ng-model="fieldVal" 
       ng-blur="validate(fieldVal)"/>

You can also use ng-model-options combined with ng-change

<input type="text" 
       ng-modle="fildsVal" 
       ng-model-option="{ updateOn: 'blur' }" 
       ng-change="validate(fieldVal)" />

I also found the debounce option very nice to trigger the validation. You can time it so that when user is done typing, the validation triggers:

<input type="text"
       ng-model-options="{ debounce: 800 }" 
       ng-pattern="/^[0-9]{1,9}$/" />
like image 33
Adam Boostani Avatar answered Sep 28 '22 05:09

Adam Boostani