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
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.
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}$/" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With