Angular form validation 2

Time:2021-6-14

preface

In previous articles《Angular form validation》This paper mainly introduces some basic knowledge about angular form verification. This article will focus on expanding the relevant content of angular form verification and the application in actual development.


Form validation scenario 1

In the actual development, we may have such a situation. We want to be able to verify after the user has finished typing and lost focus. If the verification fails, an error message is submitted. If you want to achieve this effect. You need to add a custom directive.

app.directive('ngFoucus',[function(){
var FOCUS_CLASS='ng-focused';
return{
restrict:'A',
require:'ngModel',
link:function(scope,element,attrs,ctrl){
        ctrl.$focused=false;

element.bind('focus',function(evt){
element.addclass(FOCUS_CLASS);
scope.$apply(function(){
 ctrl.$focused=true;});
}).
bind('blur',function(evt){
element.removeClass(FOCUS_CLASS);
scope.$apply(function(){
 ctrl.$focused=false;});});}}
}]);

You can use the ngfocus directive by adding it to the input element.

<input ng-class="{error:signup_form.name.$dirty&&signup_form.name.$invalid}"
  type="text"
placeholder="name"
name="name"
ng-model="signup.name"
ng-minlength="3"
ng-maxlength="200
required"
ng-focus
/>

The ngfocus directive adds corresponding behaviors to the blue and focus of the form input fields. A class named ng focused is added and the value of $focused is set to true. Next, you can display individual error messages based on whether the form has focus or not. as follows

<div class="error" ng-show="signup_form.name.$dirty&&signup_form.name.$invalid&&!signup_form.name.$focused">
</div>

Of course, you can also use the $isempty () method in ngmodel control to determine whether the input field is empty. Returns true when the input field is empty, otherwise returns false.

Form verification of angular new version

In the previous code, angular’s form validation is a relatively complex component. It’s not particularly convenient to use. It’s not concise enough.
But after the new angular Version (1.3 +), we can use a simpler way to do form validation.

ng-messages

To use the ng messages command. We have to install this module first. We can download it by ourselves, directly reference it to the page, or use it
$bower install — save angular messages
After the installation. We need to inject it into the module

angular.module('myapp',['ngMessages'])

In order to compare the previous form verification methods, here I use the old version of form verification to write an example.

/*old*/

<form name="signup_form" novalidate ng-submit="signupForm()" ng-controller="signupController">
<fieldset>
<legend>Signup</legend>
<div class="row">
<div  class="large-12 columns">
<label>Your name</label>
<input type="text" placeholder="Name" name="name" ng-model="signup.name" ng-minlength=3 ng-maxlength=20 required/>
<div class="error" ng-show="signup_form.name.$dirty&&gignup_form.name&invalid&&signup_form.submitted">
<small class="error" ng-show="signup_ Form. Name. $error. Required "> name cannot be empty < / small >
<small class="error" ng-show="signup_ Form. Name. $error. Minlength "> name too short < / small >
<small class="error" ng-show="signup_ Form. Name. $error. MaxLength "> name is too long < / small >
</div>
</div>
</div>
</fieldset>
</form>





/*new*/
<form name="signup_form" novalidate ng-submit="signupForm()" ng-controller="signupController">
<div class="row">
<div  class="large-12 columns">
<label>Your name</label>
<input type="text" placeholder="Name" name="name" ng-model="signup.name" ng-minlength=3 ng-maxlength=20 required/>
<div class="error" ng-messages="signup_form.name.$error">
< div ng message = "required" > name cannot be empty < / div >
< div ng message = "minlength" > name too short < / div >
< div ng message = "MaxLength" > name too long < / div >
</div>
</div>
</div>
</form>

With ngmessages, the form itself is simpler than before. And better understand. But there is another problem in the above code, that is, only one error message can be displayed at a time.
If we want to display all the error messages at the same time. Also simple, we just need to add ng messages multiple next to the ng messages instruction

<div class="error" ng-messages="signup_form.name.$error"  ng-messages-multiple>
< div ng message = "required" > name cannot be empty < / div >
< div ng message = "minlength" > name too short < / div >
< div ng message = "MaxLength" > name too long < / div >
</div>

If we had a lot of form pages. We can encapsulate some general verification tips into a template page

<!--in temples/errors.html-->
< div ng message = "required" > name cannot be empty < / div >
< div ng message = "minlength" > name too short < / div >
< div ng message = "MaxLength" > name too long < / div >

Then we can use the ng messages include property in the view to introduce this template to improve the structure of the form

<div class="error" ng-messages="signup_form.name.$error"  ng-messages-include="templates/errors.html"></div>

In the above examples, the verification provided by angular is combined with ng messages. How does custom validation work?
For example, I want to create a custom verification to verify whether the user name in the form is registered

/*First, create a custom directive*/
app.directive('ensureUnique',function($http){
return {
require:'ngmodel',
link:function(scope,ele,attrs,ctrl){
var url=attrs.ensureUnique;
   ctrl.$parsers.push(function(val){
 if(!val||val.length==0)
retrun;
});
ngModel.$setValidity('checkingAvailability',true);
ngModel.$setValidity('usernameAvailablity',false);
$http({
 Method:'GET',
url:url,
params:{
username:val}
}).success(function(){
 ngModel.$setValidity('checkingAvailability',false);
ngModel.$setValidity('usernameAvailablity',true);
})['catch'](function(){
 ngModel.$setValidity('checkingAvailability',false);
ngModel.$setValidity('usernameAvailablity',false);
});
retrun val;
}
}
});

/*Page HTML*/
<form name="signup_form" novalidate ng-submit="signupForm()" ng-controller="signupController" ensure-unique='/api/checkUsername.php'>
<div class="row">
<div  class="large-12 columns">
<label>Your name</label>
<input type="text" placeholder="Name" name="name" ng-model="signup.name" ng-minlength=3 ng-maxlength=20 required/>
<div class="error" ng-messages="signup_form.name.$error">
< div ng message = "required" > name cannot be empty < / div >
<div ng-message="checkingAvailability">checking</div>
< div ng message = "usernameavailability" > user name already exists < / div >
</div>
</div>
</div>
</form>

In the above usage, we checked the custom properties of the error message. To add custom error messages, we will apply them to the ngmodel of the custom insure unique directive.
So a custom validation is done. Here I just demonstrate the usage of a custom validation. There are many other advanced usages of angular ng messages, which will not be introduced here. Interested students can go to angular official website to view the document.

ending

That’s all about angular form validation. This article is written as a way of taking notes. If there are any shortcomings in the paper, please point out. If you have any questions, you can leave a message. thank you.