javascript - How to setup Angular validation to work on blur and form submit? -


angular validation works updating on model change. although displaying these validation errors upon keyup not ui friendly.

an ideal solution display error messages on blur, along on form submit. once input blurred on first time , error message displayed, input need updated on keyup/model change.

i have seen following allows model updated upon blur, not ideal solution since model updated on blur every situation.

<input type="text" name="user" ng-model="user" ng-model-options="{ updateon: 'blur' }" required> 

i came across following solution works on blur , changes keyup after error exists. although validation not apply on form submit.

http://plnkr.co/edit/vspoyo16ozq2bkall3n9?p=preview

here can have 1 angular scope variable maintain state of form submit submitted or not default variable false.

$scope.submitted = false; 

and 1 scope function validate fields on form submit. keep in mind place name attribute of form element must stetted , refereed same in function. function approach make generic. can directly write html template accessing $dirty , $error variable of input elements.

$scope.validateinput = function (name, type) {   var input = $scope.demoform[name];           return (input.$dirty || $scope.submitted) && input.$error[type]; }; 

this function called on form submission.

$scope.submitform = function () {             $scope.submitted = true;             if ($scope.demoform.$valid) {                 console.log('submitted!!');             } else {                 console.log('not valid!!');                 return false;             }         }; 

now on html template can write way .

<form name="demoform" ng-submit="submitform()" novalidate="">     <input type="text" name="name" required="" ng-model="name"/>     <span ng-show="validateinput('name', 'required')" class="text-danger">name required</span>     <button type="submit" class="btn btn-info" >save</button> </form> 

now on form submit can see validation message there if field not valid.

demo plunkr of form validation on form submit in angular


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -