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-group" ><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 class= "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><d IV class= "COL-MD-8" ><input type= "text" ng-model= "user.maxlength" ng-maxlength= "VI" 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"/></div ></div><div class= "Form-group" ><div class= "col-md-4" ><label for= "email" >5. Email </label> </div><div class= "col-md-8" ><input type= "email" id= "email" name= "email" ng-mode L= "User.email" class= "Form-control"/></div></div><div class= "Form-group" ><div class= " Col-md-4 "><label for=" age ">6. Digital </label> </div><div class= "col-md-8" ><input type= "number" id= "Age" name= "age" ng-model= "us Er.age "class=" Form-control "/></div></div><div class=" Form-group "><div class=" col-md-4 " ><label for= "url" > 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><div class=" Form-group text-center "><input class=" btn btn-primary btn-lg "type=" Submit "value=" Submit "/></div></form></div> <div class= "col-md-12" > 1. Required fields:{{user.name}}<br> 2. Minimum length =5:{{user.minlength}}<br> 3 maximum length =20:{{user.maxlength}}<br> & nbsp 4. Pattern matching:{{user.pattern}}<br> 5. e-mail:{{user.email}}<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:
<! DOCTYPE html>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 Ru Les 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 { & nbsp require: "Ngmodel", link:function (scope, element, attr, Ngmodel) { if (Ngmodel) { var Emailsregexp =/^ ([a-z0-9!#$%& ' *+\/=?^_ ' {|} ~.-][email protected][a-z0-9-]+ (\.[ a-z0-9-]+) *[;;]?) +$/i; &NBSP,} var CustomValidator = Fu Nction (value) { var validity = Ngmodel. $isEmpty (value) | | e Mailsregexp.test (value); ngmodel. $setValidity ("Multipleemail", validity); return validity? value:undefined; &NBSp }; 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 mailbox addresses , to ";" or ";" Split "/> Validation passed: {{custom_form.user_email. $valid}} </div></div><div class=" f Orm-group text-center "><input class=" btn btn-primary btn-lg "ng-disabled=" Custom_form. $invalid "type=" Submit " Value= "Submit"/></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 $viewvalueThe $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.
$parsersThe 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.
$formattersThe 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.
$viewChangeListenersThe 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.
$pristineThe value of the $pristine is Boolean and can tell us whether the user has modified the control.
$dirtyThe 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.Angularjs Form Validation