The form validation feature used in Angularjs "Go"

Source: Internet
Author: User
Tags button type

The validation feature is one of the coolest features in Angularjs, which allows you to write a web app with a good user experience.

In Angularjs, there are many instructions for validation. We'll start by learning some of the most popular built-in directives and then create a custom validation rule directive.

<form name= "Form" >  <label name= "email" >your email</label> <input  type= "email" name= " Email "ng-model=" email "placeholder=" email Address "/></form>

Angularjs allows us to easily handle client-side validation. While we cannot rely on client-side validation to secure our Web applications, they provide a good user experience.

We must first ensure that the label on the form has a name attribute, as in the example above.

We can do some basic validation, such as the minimum length, maximum length, and so on, which are HTML5 property validation features.

Tips: It is often necessary to add attributes to the form label novalidate , which disables the browser's own validation function, which is provided using ANGULARJS.

Here's a look at what validation we can set in input:

Must fill in

To verify that you have entered text, simply add required to the label:

<input type= "text" required/>
Minimum length

Verify that at least enter {number} characters, using the directive ng-minlength= "{Number}":

<input type= "text" ng-minlength=5/>
Maximum length

Verify that you enter {number} characters and use the instruction Ng-maxlength= "{number}":

<input type= "text" ng-maxlength=20/>
Regular match

Make sure the input matches a regular expression, using directives ng-pattern="/PATTERN/" :

<input type= "text" ng-pattern= "/a-za-z/"/>
Email

Verify that input is an email and set the Type property of input to email:

<input type= "Email" name= "email" ng-model= "User.email"/>
Digital

Verify that the input is a number, set the Type property of input to #:

<input type= "number" name= "number" ng-model= "User.age"/>
Url

Verify that the input is a URL, set the Type property of input to URL:

<input type= "url" name= "homepage" ng-model= "User.facebook_url"/>
Custom validation

Angularjs can easily use directives to add custom validations. For example, we want to verify that our user name is available (not duplicated in the database). To do this, we will implement an instruction that triggers an AJAX request when the input character changes:

var app = Angular.module (' Validationexample ', []) app.directive (' Ensureunique ', [' $http ', function ($http) {  return {    require: ' Ngmodel ',    link:function (scope, ele, Attrs, c) {      scope. $watch (Attrs.ngmodel, function () {        $http {          method: ' POST ',          URL: '/api/check/' + attrs.ensureunique,          data: {' field ': Attrs.ensureunique}        ). Success (function (data, status, headers, cfg) {          c. $setValidity (' unique ', Data.isunique);        }). Error (function (data, status, headers, cfg) {          c. $setValidity (' unique ', false);});});}}  ]);
Verifying form Status

Angularjs saves the results of the DOM validation in the $scope object. This allows us to make some real-time processing. The attributes provided to us are:

Note that this is the format of this property:

FormName.inputFieldName.property
Forms that have not been modified

Indicates whether the user modified the form. If ture, indicates that it has not been modified:

Formname.inputfieldname. $pristine;
Modified form

When and whether the user has modified the form:

Formname.inputfieldname. $dirty
Validated forms

Indicates whether to pass validation:

Formname.inputfieldname. $valid
Forms that failed validation

Indicates whether validation is passed. If the form does not currently pass validation, he will be true:

Formname.inputfieldname. $invalid

The last two properties are especially useful for displaying or hiding DOM elements. Of course, they are also useful if you want to set a specific class.

Error

Another useful property is the $error object provided by Angularjs. This object contains a collection of each invalid input validation. To access this property, use the following syntax:

Formname.inputfieldname. $error

If the validation fails, this property will be true (because of length>0).

Control the style when validating

When Angularjs processes validation, it adds some specific class attributes based on the status of the validation.

These class are:

. ng-pristine {}.ng-dirty {}.ng-valid {}.ng-invalid {}

These classes correspond to the results of their corresponding validation objects.

When a field is invalid, it .ng-invalid will be applied to this field. We can use CSS to set these class styles:

Input.ng-invalid {  border:1px solid red;} Input.ng-valid {  border:1px solid green;}

Let's try it all together.

Let's write a registration form. This application form will include name, Email, and user name.

Let's define a form form:

<form name= "Signup_form" Novalidate ng-submit= "Signupform ()" >  <fieldset>    <legend>signup </legend>    <button type= "Submit" class= "button radius" >Submit</button>  </fieldset> </form>

The name of this form is signup_form that we will call when we click Submit signupForm()方法 .

Now, let's add the user's name:

<div class= "Row" >  <div>    <label>your name</label>    <input type= "text"         Placeholder= "name"         name= "name"         ng-model= "Signup.name"         ng-minlength=3         ng-maxlength=20 required />  </div></div>

We added an input box named name, and bound the object on the Signup.name object of the $scope object (via Ng-model).

We have also set up several validations. These validations are: must have a name of 3 or more in length. and a maximum length limit of 20 characters. Finally, the name should be required.

Let's use properties to control the display or hide the error message. We will also use the $dirty property to ensure that the error message does not appear until the user has entered the character:

<div class= "Row" >  <div>    <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 && signup_form.name. $invalid" >    <small class= "error"         ng-show= "signup_form.name. $error. Required" >        Your name is required.    </small>    <small class= "error"             ng-show= "Signup_form.name. $error. minlength" >            Your Name is required to being at least 3 characters    </small>    <small class= "error"             ng-show= "Signup_ Form.name. $error. MaxLength ">            Your name cannot be longer than characters    </small>  </div >  </div></div>

Let's take a look at email verification:

<div class= "Row" > <div> <label>your email</label> <input type= "email" pl    aceholder= "Email" name= "email" ng-model= "Signup.email" ng-minlength=3 ng-maxlength=20 required/>  <div class= "error" ng-show= "Signup_form.email. $dirty && signup_form.email. $invalid" > <small      class= "Error" ng-show= "Signup_form.email. $error. Required" > Your email is required. </small> <small class= "error" ng-show= "Signup_form.email. $error. minlength" > You R email is required to being at least 3 characters </small> <small class= "error" ng-show= "sig Nup_form.email. $error. Email "> That's not a valid email.      Please input a valid email. </small> <small class= "error" ng-show= "Signup_form.email. $error. maxlength" > You   R email cannot be longer than characters   </small> </div> </div></div> 

The form validation feature used in Angularjs "Go"

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.