Form Validation <AngularJs>

Source: Internet
Author: User

Common Forms Validation Directive 1. Mandatory fields Validation

If a form input is filled in, simply add the HTML5 tag to the input field element required:

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

To verify that the text entered by the form is longer than a certain minimum value, use the directive ng-minleng= "{number}" on the input field:

3. Maximum length

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

<input type= "text" ng-maxlength= "/>"
4. Pattern matching

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

5. Email

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

6. Digital

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

7. URL

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

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

Let's test this out by putting these forms validation into a specific implementation:

  <div class= "col-md-6" > <form role= "Form" class= "Form-horizontal" > <div class= "Form-grou                P "> <div class=" col-md-4 "> <label for=" Name ">1. Required Fields </label> </div> <div class= "col-md-8" > <input class= "Form-control" id= "name "Type=" text "required ng-model= ' User.Name '/> </div> </div> <div C lass= "Form-group" > <div class= "col-md-4" > <label for= "minlength" >2. Min. length =5 </label> </div> <div class= "col-md-8" > <input type= "            Text "id=" minlength "ng-minlength=" 5 "ng-model=" User.minlength "class=" Form-control "/> </div>                    </div> <div class= "Form-group" > <div class= "col-md-4" > <label for= "MinleNgth ">3. Maximum length =20</label> </div> <div class=" Col-md-8 "> <            Input type= "text" ng-model= "User.maxlength" ng-maxlength= "class=" Form-control "/>" </div>                    </div> <div class= "Form-group" > <div class= "col-md-4" > <label for= "MinLength" >4. Pattern matching </label> </div> <div class= "col-md-8" > <input type= " Text "id=" minlength "ng-model=" User.pattern "ng-pattern="/^[a-za-z]*\d$/"class=" Form-control "/> </d                    iv> </div> <div class= "Form-group" > <div class= "col-md-4" > <label for= "Email" >5. Email </label> </div> <div class= "col-md-8" > <input type= "em Ail "id=" email "name=" email "ng-model=" User.email "class=" Form-control"/> </div> </div> <div class=" Form-group "> <d IV class= "COL-MD-4" > <label for= "Age" >6. Digital </label> </div> <div class= "col-md-8" > <input type= "Numb             Er "id=" age "name=" Age "ng-model=" User.age "class=" Form-control "/> </div> </div> <div class= "Form-group" > <div class= "col-md-4" > <label for= "u RL "> 7. url</label> </div> <div class= "col-md-8" > <input type= "url "id=" url "name=" homepage "ng-model=" User.url "class=" Form-control "/> </div> </div&            Gt <div class= "Form-group text-center" > <input class= "btn btn-primary btn-lg" type= "Submit" value= "submitted "/> </div> </form> </div> <div class= "col-md-12" > 1. Required fields:{{user.name}}<br> 2. Minimum length =5:{{user.minlength}}<b R> 3. Maximum length =20:{{user.maxlength}}<br> 4. Pattern matching:{{user.pattern}}<br> 5. E-mail: {{user.email}}& Lt;br> 6. Digital:{{user.age}}<br> 7.url:{{user.url}}<br> </div>

In the test we found that only if the expression satisfies the validation, the two-way binding will be done in real time. We also found, as follows:

There doesn't seem to be a problem, but if we transplant it to a team HTML5 verify that the browser is not good to test "This example IE9", the problem is, some fields are completely out of verification

In fact, in the example above, we used the HTML5 validation to combine with Ng's own validation, which does not support HTML5 verification, but the NG free verification works well. The solution is simple, you can use pattern matching to resolve these situations, or you can customize validation instructions to write or redefine validation rules.

Block browser's default authentication behavior for forms

To add a novalidate tag to a FORM element, the question is how do we know which fields are valid for our form and which are illegal or invalid? Ng also provides a great solution for this, where the properties of the form can be accessed in the $scope object to which they belong, and we can access the $scope object, so that JavaScript can indirectly access the form properties in the DOM. With these properties, we can respond to the form in real time.

These properties can be accessed using the FormName.inputFieldName.property format.

Forms that have not been modified

A Boolean property that indicates whether the user modified the form. If ture, indicates that no modification has been done; false indicates modified:

Formname.inputfieldname. $pristine;
Modified form

The Boolean attribute, when and only if the user has actually modified the form. Regardless of whether the form passes validation:

Formname.inputfieldname. $dirty

Validated forms

A Boolean property that indicates whether the form passes validation. If the form is currently validated, he will be true:

Formname.inputfieldname. $valid
Forms that failed validation
Formname.inputfieldname. $invalid

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

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

If the validation fails, the value of this property is true, and if the value is false, the value of the input field is validated.

Here we test these validation instructions:

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code

The effect is as follows:

At the same time, Ng has set some CSS styles for these kinds of verification instructions.

They include:

. ng-valid         {  }.ng-invalid     {  }.ng-pristine     {  }.ng-dirty         {  }/* really specific CSS Rules applied by angular */.ng-invalid-required         {  }.ng-invalid-minlength         {  }.ng-valid-max-length         {  }

They correspond to the specific state of the form input field.
For example, when the input in a field is illegal, the. Ng-invlid class is added to this field. You can edit your favorite CSS. You can customize these classes privately to implement specific scenario applications.

However, the default validation directives are not necessarily able to fully meet our real-world scenarios, and Ng also provides the functionality of custom validation directives.

First, let's look at a simple example:

Angular.module ("MyTest", [])  . Directive (' multipleemail ', [function () {      return {          require: ' Ngmodel ',          link:function (scope, element, attr, Ngmodel) {              if (Ngmodel) {                  var emailsregexp =/^ ([a-z0-9!#$%& ' *+\/= ?^_`{|} ~.-][email protected][a-z0-9-]+ (\.[ a-z0-9-]+) *[;;]?) +$/i;              }              var CustomValidator = function (value) {                  var validity = Ngmodel. $isEmpty (value) | | | emailsregexp.test (value)                  ; Ngmodel. $setValidity ("Multipleemail", validity);                  return validity? value:undefined;              };              Ngmodel. $formatters. push (CustomValidator);              Ngmodel. $parsers. push (CustomValidator);}}      ;  }])

The page HTML section code is as follows:

<form class= "form-horizontal" role= "form" id= "Custom_form" name= "Custom_form" novalidate> <div class=            " Form-group ">                <label class=" col-sm-2 Control-label "> Multiple email</label> <div                class=" Col-sm-10 ">                    <input multiple-email name=" User_email "ng-model=" User.email "required class=" Form-control " Placeholder= "Custom authentication, multiple email addresses to"; "or"; " Split "/>                    validation passed: {{custom_form.user_email. $valid}}                </div>            </div>            <div class=" Form-group  text-center ">                <input class=" btn btn-primary btn-lg "ng-disabled=" Custom_form. $invalid " Type= "Submit" value= "Submission"/>            </div>        </form>

The code is very simple, and the effect of the implementation is as follows:

This code is simple, but involves several important attributes of Ngmodelcontroller $viewvalue

The $viewValue property holds the actual string required to update the view.

$modelValue

$modelValue is held by the data model. The $modelValue and $viewvalue may be different depending on whether the $parser pipeline is operating on it.

$parsers

The value of $parsers is an array of functions that, when the user interacts with the controller, and the $setViewValue () method in Ngmodelcontroller is called, the function in which the user interacts with the controller, and the $setviewvalue () method in Ngmodelcontroller is called in the form of pipelining. Ngmodel the value read from the DOM is passed to the function in the $parsers and is processed sequentially by the parser in it. This is to manipulate and decorate the values.

Note: the Ngmodel. $setViewValue () function is used to set the view values in the scope.

Ngmodel. $set the Viewvalue () function can accept a parameter.

Value (String): The value parameter is the actual value that we want to assign to the Ngmodel instance.

This method updates the local $viewvalue on the controller and then passes the values to each of the $parser functions (including validators). When the value is parsed and all functions in the $parser pipeline are completed, the values are assigned to the $modelvalue property and passed to the expression provided by the Ng-model property in the directive. Finally, when all the steps are complete, all listeners in the$viewChangeListeners are called. Note that calling $setviewvalue () alone does not evoke a new digest loop, so if you want to update the instruction, you need to manually trigger digest after setting $viewvalue. The $setViewValue () method is suitable for listening to custom events in custom directives (such as using a jquery plug-in with callback functions), and we want to set $viewvalue and execute digest loops at callback.

$formatters

The value of $formatters is an array of functions, where functions are invoked one at a time as the value of the data model changes in the Pipelined form. It has no effect on the $parser pipeline and is used to format and convert values to be displayed in the control that binds the value.

$viewChangeListeners

The value of $viewChangeListeners is an array of functions, where functions are invoked one at a time in a pipelined manner when the values in the view change. With $viewchangelisteners, similar behavior can be achieved without the use of $watch. Because the return values are ignored, these functions do not require a return value.

$error

$error Object holds the validator name without validation and the corresponding error message.

$pristine

The value of the $pristine is Boolean and can tell us whether the user has modified the control.

$dirty

The value of $dirty, in contrast to $pristine, tells us whether the user has interacted with the control.

$valid

$valid value can tell us if there are errors in the current control. When there is an error value of false, there is no error value of true.

$invalid

$invalid value tells us if there is at least one error in the current control, and its value is the opposite of $valid.

After learning the basic knowledge point, it is necessary to study the custom validation in depth, and the usability of the verification instruction has been improved after ng1.3.

Form Validation <AngularJs>

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.