Angularjs Form Validation

Source: Internet
Author: User
Tags form input text

Reprint Please specify the source http://www.023996.cn/hyxw/s1129.html

Anjularjs Form Validation

It is important to be able to give real-time visual feedback based on what the user has entered in the form. In the context of human-to-human communication, feedback from forms validation is as important as getting the correct input.

Forms validation not only provides users with useful feedback, but also protects our web applications from malicious or faulty input. We try to protect the backend at the Web front end.

Angularjs is able to use the HTML5 form verification function with its own verification instructions and is very convenient. ANGULARJS provides a number of form validation directives.

<formname= "form"novalidate>    <labelname= "Email">Your Email</label>    <inputtype= "Email"name= "Email"Ng-model= "Email"placeholder= "Email Address"/></form>

To use form validation, first make sure that the form has a Name property as in the example above.

All input fields are available for basic validation, such as maximum, minimum length, and so on. These features are provided by the new HTML5 form properties.

If you want to block the browser's default validation behavior for forms, you can add novalidate tags to the form elements

1. Required Fields required

Verify that a form input is filled in, as long as you add the HTML5 tag to the input field element required:

  Note: The Required property applies to the following <input> types: text, search, URL, telephone, email, password, date pickers, number, checkbox, Radio and file

<type= "text"/>

   

2. Minimum length ng-minleng= "{Number}"

Verify that the form input text length is greater than a minimum value, use the ANGULARJS directive ng-minleng= "{number}" on the input field

<type= "text"  ng-minlength= "5"/>

 

3. Maximum length ng-maxlength= "{Number}"

To verify that the text length entered by the form is less than or equal to a maximum value, use the ANGULARJS directive ng-maxlength= "{number}" on the input field

<type= "text"  ng-maxlength= "/> "

4. Pattern matching ng-pattern= "/pattern/"

Use ng-pattern= "/pattern/" to ensure that the input matches the specified regular expression:

<type= "text"  ng-pattern= "[A-za-z]"/>

  

5. Email

Verify that the input is an e-mail message, as long as you set the type of input to email as follows:

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

6. Digital

Verify that the input is numeric and set the type of input to number:

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

7. URL

Verify that the input is a URL and set the type of input to a URL:

<type= "url"  name= "homepage"  Ng-model = "User.facebook_url" />

Controlling variables in forms

The properties of a form can be accessed in the $scope object to which it belongs, and we can access $scope objects, so JavaScript can indirectly access form properties in the DOM. With these properties, we can respond to the form in real time (as with anything else in Angularjs). These properties include the following. (Note that these properties can be accessed using the following format.) )

FormName.inputFieldName.property

Non-modified form

This is a Boolean property that is used to determine whether the user has modified the form. If not modified, the value is true if the modified value is False

Formname.inputfieldname. $pristine

Modified form

This value returns true whenever the user modifies the form, regardless of whether the input passes validation

Formname.inputfieldname. $dirty

Legal Forms

This Boolean property is used to determine whether the contents of the form are legitimate. If the current form content is legal, the value of the following property is true:

Formname.inputfieldname. $valid

Illegal forms

This Boolean property is used to determine whether the contents of the form are illegal. If the current form contents are illegal, the value of the following property is true:

Formname.inputfieldname. $invalid

Error

This is another very useful property provided by Angularjs: $error object. It contains all of the validation content for the current form, as well as information about whether they are legitimate. Use the following syntax to access this property:

Formname.inputfieldname. $error

$parsers

When the user interacts with the controller, and the $setViewValue () method in Ngmodelcontroller is called, the functions in the $parsers array are called one by one, in the form of pipelining. When the first $parse is called, the execution results are passed to the second $parse, and so on

These functions can convert the input values, or set the legitimacy of the form through the $setValidity () function.

Using $parsers arrays is one way to implement custom validation.

For example, suppose we want to make sure that the input value is between a number of values, and that a new function can be stacked in the $parsers array, and this function is called in the validation chain.

The value returned by each $parser is passed into the next $parser. Returns undefined when you do not want the data model to update.

Html

<!DOCTYPE HTML><HTMLNg-app= "MYAPP"><Head>    <MetaCharSet= "Utf-8">    <Metahttp-equiv= "X-ua-compatible"content= "Ie=edge">    <title>Form Testing</title>    <Linkrel= "stylesheet"href="">    <Scripttype= "Text/javascript"src= "Angular.1.2.13.js"></Script></Head><Body>    <DivNg-controller= "TestController">        <formname= "Testform">            <inputtype= "Number"name= "Inputs"ng-test Ng-model= "Obj.number">            <spanNg-show= "testform.inputs. $error. Test">Good</span>            <spanNg-hide= "testform.inputs. $error. Test">AaG</span>            <Div>{{testform.inputs. $valid}}</Div>            <Div>{{testform.inputs. $invalid}}</Div>            <Div>{{Obj.number}}</Div>        </form>    </Div>    <Scripttype= "Text/javascript"src= "Test5app.js"></Script></Body></HTML>

JavaScript (test5app.js)

Angular.module (' myApp ', []). Controller (' TestController ',function($scope) {$scope. obj={number:34}}). directive (' Ngtest ',function() {    return{require:'? Ngmodel ', restrict:' AE ', Link:function($scope, IELM, Iattrs, Ngmodel) {if(!ngmodel)return; Ngmodel. $parsers. Push (function(viewvalue) {varnum =parseint (Viewvalue); if(num >= 0 && num < 99) {Ngmodel. $setValidity (' Test ',true); returnViewvalue}Else{Ngmodel. $setValidity (' Test ',false); returnundefined}}) }    }});

Angularjs 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.