Angular form Validation

Source: Internet
Author: User

When using AngularJS for development, form filling is a very common requirement, and form verification is a more troublesome part, this article makes a summary.

The form used in the Angular view is not a normal form in HTML, but an instruction that has been encapsulated by Angular. It can accomplish functions that cannot be achieved by ordinary form, such as form nesting, and its own powerful authentication function.

Angular is used when checking the form ngModelController , and if not set ng-model , Angular cannot know if the form.$invalid value is true. Back in the custom validation there is an introduction to it.

This article was used in the validation of the form ng-messages , and at the end of the article there was an introduction to it.

This article relates to the source code here, the implementation of the effect here.

Native form Validation

At the form level, you can use ng-disabled to control the state of the Submit button, which is not clickable until all the form list items have been validated, and the general table item validation options are described below.

Input validation Options

The AngularJS input tag comes with the following validation options.

<Inputng-model= "" [name= [required= [ng-required= [ng-minlength= "" [ng-maxlength=] [ ng-pattern= "" [ng-change=]> </INPUT>          

A. Required fields

<input type="text" name="myName" ng-model="username" required />

Use ng-required the values that can be set based on the value of the following expression required .

requiredfor when not satisfied form.myName.$error {required: true} .

B. Length

<input type="text" name="myName" ng-model="username" ng-minlength="2" ng-maxlength="10" />

When not satisfied ng-minlength / ng-maxlength time form.myName.$error is {minlength: true, maxlength: true} .

Direct use minlength / maxlength also has the same effect, and maxlength can be set to enter a maximum of x characters, beyond which cannot be entered.

C. Pattern matching

<input type="text" name="myDesc" ng-model="desc" ng-pattern="/^[a-zA-Z]{1,20}$/" />

ng-patternfor when not satisfied form.myName.$error {pattern: true} .

D. Other

AngularJS also checks for a specific format. For example, it will be type set to url , and email so on, without special verification requirements, you can directly use these self-check, or modify the Angular built-in validator through custom directives. Different types have different validation options, specifically refer to the AngularJS API documentation.

CSS Classes

Angular automatically adds the following sets of styles to forms and form items based on form status:

    • ng-validThe validation passes, and the opposite isng-invalid

    • ng-valid-[key]The value passed by the validation added by the custom validator, relative to theng-invalid-[key]

    • ng-pristineThe non-interactive state, in contrast to theng-dirty

    • ng-touchedis not in the state of access, relative tong-untouched

    • ng-pendingMeet $asyncValidators The situation

These have corresponding values in the properties of the Ngmodelcontroller.

Depending on the class, you can set different styles for different states, such as this:

input.ng-valid.ng-dirty {    border-color: #78FA89;}input.ng-invalid.ng-dirty { border-color: #FA787E;}
Custom validation

In the article on getting started with the AngularJS directive, it has been mentioned that through the Require property and controller parameters, the interaction between instructions can be implemented. Then, an instance of the require: ‘ngModel‘ Controller property of the directive can be used in a custom directive ngModel .

Ngmodelcontroller

Ngmodel provides data binding, validation, CSS updates, data formatting, and compilation operations. The following is a brief introduction to the properties and methods commonly used by Ngmodelcontroller.

Core Properties
    1. $viewValueValues in the View

    2. $modelValueValues in the data model

inputwhen the event is triggered, $viewValue it is synchronized to $modelValue . By default, this is triggered when input there is a change in the content. AngularJS 1.3 has been introduced ng-model-options , allowing this synchronization to be deferred to blur or after a certain amount of delay.

 <input  Type= "text" name= "username" ng-model= "username"  Ng-model-options= "{updateon: ' Blur '}" >< input type= "text" name=" username "ng-model=  "username" ng-model-options= "{ debounce:500} "             

$viewValuewhen the value is synchronized to $modelValue , it passes through $parsers , and the $validators $asyncValidators three core pipes (the latter two are newly added after AngularJS 1.3) are processed and then updated to the $modelValue top (if the validator pipeline fails, it is not updated).

Core pipeline
    1. $parsersChanging the format of the view values and updating them to the model, in $viewValue $modelValue contrast, is just the opposite $formatters .

    2. $validatorsUsed to add a synchronization validator

    3. $asyncValidatorsUsed to add an asynchronous validator

Common Properties
    1. $errorThe validator name and the corresponding error message are not passed

    2. $validWhether the form item is validated, passed as true, is relative to the$invalid

    3. $touchedWhether the form item has been accessed, if the focus is obtained, the value is true when it is lost, relative to$untouched

    4. $dirtyIndicates whether the user has interacted with the form item (such as entering something), and as long as there is any change, the value is true, relative to the$pristine

Common methods
    1. $renderDefine how views are rendered in a specific way

    2. $setViewValueSet the view value (requires a manual trigger $digest ), using the scene to listen for custom events in custom directives (e.g. using a jQuery plugin with callbacks)

Custom Synchronization Validation & asynchronous validation

ngModelControlleras mentioned in, AngularJS 1.3 provides the validator pipeline, which only needs to be added to the synchronization verification $validators .

For example, there is a common need, for a required name table item, requires only input in English, the minimum length is 2 characters, then this can be achieved.

Instructions:

App.directive (' Namecheck ', namecheck); namecheck. $inject = [' $http ',' $q '];functionNamecheck($http, $q) {var Name_reg =/^[a-za-z\u4e00-\u9fa5]+$/;return {restrict:' A ',Require' Ngmodel ', Link:function($scope, Element,attrs,ctrl) {Synchronize validation ctrl. $validators. Char =function(Modelvalue, Viewvalue) {var value = Modelvalue | | Viewvalue;if (!name_reg.test (value)) {return FALSE;} return true;}; //asynchronously validates ctrl. $asyncValidators. exist =  function (Modelvalue, Viewvalue) { var value = Modelvalue | | viewvalue; var deferred = $q. Defer (); $http. Get ( ' api/users/' + value). Then (function (res) {if (res.data.isExist) {deferred.reject (false);} deferred.resolve (true); }) return Deferred.promise;}} }} 

Main Page:

<FormName="MyForm" ><Divclass="Form-group" ><InputType="Text"Name="Username"ng-model="username" class="Form-control" name-check minlength="2" required>  <span ng-messages= "myform.username. $error" ng-messages-include= "error.html " ng-show="myform.username. $touched" > </span> </div> </form >                   

Error Message page:

<span  Ng-message= "required" > Required </span ><span ng-message= "char" > Illegal character </span> <span ng-message=" minlength "> Too Short </span> <span ng-message=" exist "> name already exists </SPAN>     
Ngmessages

ng-messagesis a module that AngularJS 1.3 provides to enhance the template display, mainly used to handle complex error messages.

In previous versions, if you wanted to handle the display of error messages, you might need to define a bunch code of complex ng-if statements to implement. Also, the priority of error message display cannot be controlled when the input satisfies multiple error rules. These, the use ng-messages can be solved perfectly.

Preparatory work
    1. Introducedangular-messages.js

    2. Add Dependencies:angular.module(‘app‘, [‘ngMessages‘])

How to use

There are two ways to use it, one to ng-messages use as a property directive:

<FormName="MyForm" ><InputType="Text"Ng-model="Field"Name= "MyField" required minlength=  "5"/> <div ng-messages= "Myform.myfield. $error" > <div ng-message=  "required" > Required </div> <div ng-message=  "minlength" > length not enough </div> </div></ Form>               

This will be a single display in the order in which each error message is written, and if you want to display all the error messages simultaneously, add ng-messages-multiple :

<div ng-messages="myForm.myField.$error" ng-messages-multiple></div>

The other is ng-messages used as an element directive:

<ng-messages for="myForm.myField.$error">    <ng-message when="required">必填</ng-message> <ng-message when="minlength">长度不够</ng-message></ng-messages>

If the error message is the same for many form items, you can also put the error message in the template and use the ng-messages-include instruction to refer to it:

<div ng-messages="myForm.username.$error" ng-messages-include="validateTemplate/error.html"></div>

Error template file:

<div ng-message="required">必填</div><div ng-message="minlength">长度不够</div>

A more detailed use of the angular-messages.js source files can be directly read the comments.

Angular form Validation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.