Common form verification instructions
1. Required verification
Whether a form input has been filled in, just add the HTML5 tag required to the input field element:
Copy the code as follows:<input type="text" required />
2. Minimum length
Verify that the text length of the form input is greater than a certain minimum value, and use the instruction ng-minleng= "{number}" on the input field:
Copy the code as follows:<input type="text" ng-minlength="5" />
3. Maximum length
Verify that the text length of the form input is less than or equal to a certain maximum value, and use the instruction ng-maxlength="{number}" on the input field:
Copy the code as follows:<input type="text" ng-maxlength="20" />
4. Pattern matching
Use ng-pattern="/PATTERN/" to ensure that the input matches the specified regular expression:
Copy the code code as follows:<input type="text" ng-pattern="/[a-zA-Z]/" />
5. Email
Verify that the input content is an email, just set the input type to email like below:
Copy the code as follows:<input type="email" name="email" ng-model="user.email" />
6. Numbers
Verify that the input content is a number and set the input type to number:
Copy the code as follows:<input type="number" name="age" ng-model="user.age" />
7. URL
Verify that the input content is a URL and set the input type to url:
Copy the code as follows:<input type="url" name="homepage" ng-model="user.facebook_url" />
Let's test these form verifications in specific implementations:
<div> <form role="form"> <div> <div> <label for="name">1.Required</label> </div> <div> <input id="name" type="text" required ng-model='user.name' /> </div> </div> <div> <div> <label for="minlength">2. Minimum length=5</label> </div> <div> <input type="text" id="minlength" ng-minlength="5" ng-model="user.minlength" /> </div> </div> <div> <label for="minlength">3.Maximum length=20</label> </div> <div> <input type="text" ng-model="user.maxlength" ng-maxlength="20" /> </div> </div> <div> <div> <label for="minlength">4. Pattern matching</label> </div> <div> <input type="text" id="minlength" ng-model="user.pattern" ng-pattern="/^[a-zA-Z]*/d$/" /> </div> </div> <div> <div> <label for="email">5. Email</label> </div> </div> <div> <label for="email">5. Email</label> </div> <div> <input type="email" id="email" name="email" ng-model="user.email" /> </div> </div> <div> <div> <label for="age">6. Number</label> </div> <div> <input type="number" id="age" name="age" ng-model="user.age" /> </div> </div> <div> <div> <label for="url"> 7. URL</label> </div> <div> <input type="url" id="url" name="homepage" ng-model="user.url" /> </div> </div> <div> <input type="submit" value="submit" /> </div> </form> </div> <div> 1. Required fields: {{user.name}}<br> 2. Min. length=5:{{user.minlength}}<br> 3. Maximum length=20:{{user.maxlength}}<br> 4. Pattern matching: {{user.pattern}}<br> 5. Email: {{user.email}}<br> 6. Number: {{user.age}}<br> 7.URL:{{user.url}}<br> </div>In the test, we found that two-way binding will be performed in real time only when the expression satisfies verification. At the same time, we also found that the renderings are as follows:
Nothing seems to have happened, but if we port it to a browser with a team of HTML5 verification that is not very good, let's test it [IE9 in this example], the problem is that some fields are not verified at all.
In fact, in the above example, we used HTML5 verification and ng's own verification to combine it. It does not support HTML5 verification, but ng's free verification runs well. The solution is very simple. You can use pattern matching to solve these situations, or you can customize verification instructions to rewrite or redefine verification rules.
Block the default verification behavior of the browser for forms
Just add the novalidate tag on the form element. The question is how do we know which fields in our form are valid, and which things are illegal or invalid? ng also provides a great solution for this. The properties of the form can be accessed in the $scope object to which it belongs, and we can access the $scope object, so JavaScript can indirectly access the form properties in the DOM. With these properties, we can respond in real time to the form.
These properties can be accessed using the format formName.inputFieldName.property.
Unmodified form
Boolean property indicating whether the user has modified the form. If it is ture, it means that it has not been modified; false means that it has been modified:
The code copy is as follows: formName.inputFieldName.$pristine; modified form
Boolean property if and only if the user has actually modified the form. Regardless of whether the form is verified or not:
The code copy is as follows: formName.inputFieldName.$dirty
Verified form
Boolean property that indicates whether the form has passed the verification. If the form is currently validated, it will be true:
The copy code is as follows: formName.inputFieldName.$valid The copy code is as follows: formName.inputFieldName.$invalid
The last two properties are particularly useful when used for display or hiding the DOM element. At the same time, they are also very useful if you want to set up a specific class.
mistake
This is another very useful property provided by AngularJS: the $error object. It contains all the verification content of the current form, as well as information on whether they are legitimate. Access this property using the following syntax
The code copy is as follows: formName.inputfieldName.$error
If the verification fails, the value of this property is true; if the value is false, it means that the value of the input field has passed the verification.
Below we test these verification instructions:
<!DOCTYPE html><html ng-app="myTest"> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <link href="~/Content/css/bootstrap.min.css" rel="stylesheet" /> <script src="~/Javascript/angular.min.js"> </script> <style type="text/css"> body { padding-top: 30px; } </style> </head> <body ng-Controller="MyController"> <div> <form role="form" name="myForm" ng-submit="submitForm(myForm.$valid)" novalidate> <div> <div> <label for="name">1.Required</label> </div> <div> <input id="name" name="name" type="text" required ng-model='user.name' /> <span ng-show="myForm.name.$dirty && myForm.name.$valid"></span> </div> </div> <div> <div> <label for="minlength">2. Minimum length=5</label> </div> <div> <input type="text" id="minlength" name="minlength" ng-minlength="5" ng-model="user.minlength" /> <span ng-show="myForm.minlength.$dirty && myForm.minlength.$valid"></span> </div> </div> <div> <div> <label for="maxlength">3.Maximum length=20</label> </div> <div> <input type="text" id="maxlength" name="maxlength" ng-model="user.maxlength" ng-maxlength="20" /> <span ng-show="myForm.maxlength.$dirty && myForm.maxlength.$valid"></span> </div> </div> <div> <div> <label for="pattern">4. Pattern Matching</label> </div> <div> <input type="text" id="pattern" name="pattern" ng-model="user.pattern" ng-pattern="/^[a-zA-Z]*/d$/" /> <span ng-show="myForm.pattern.$dirty && myForm.pattern.$valid"></span> </div> </div> <div> <div> <label for="email">5. Email</label> </div> <div> <input type="email" id="email" name="email" ng-model="user.email" /> <span ng-show="myForm.email.$dirty && myForm.email.$valid"></span> </div> </div> <div> <div> <label for="age">6. Number</label> </div> <div> <input type="number" id="age" name="age" ng-model="user.age" /> <span ng-show="myForm.age.$dirty && myForm.age.$valid"></span> </div> </div> <div> <label for="url"> 7. URL</label> </div> <div> <input type="url" id="url" name="url" ng-model="user.url" /> <span ng-show="myForm.url.$dirty && myForm.url.$valid"></span> </div> </div> <div> <input ng-disabled="myForm.$invalid" type="submit" /> </div> </form> </div> <div> 1. Required fields: {{user.name}} $pristine [Not modified]: {{myForm.name.$pristine }} $dirty [Modified]: {{myForm.name.$dirty}} $invalid [Verification failed]: {{myForm.name.$invalid}} $invalid [Verification successful]: {{myForm.name.$valid}} required: {{myForm.name.$error.required}} <br> 2. Minimum length=5:{{user.minlength}} $pristine [Not modified]: {{myForm.minlength.$pristine }} $dirty【Modified】: {{myForm.minlength.$dirty}} $invalid【Verification failed】: {{myForm.minlength.$invalid}} $invalid【Verification successful】: {{myForm.minlength.$valid}} $error【Error details】: {{myForm.minlength.$error}}<br> 3. Maximum length=20:{{user.maxlength}} $pristine 【Not modified】: {{myForm.maxlength.$pristine }} $dirty【Modified】: {{myForm.maxlength.$dirty}} $invalid【Verification failed】: {{myForm.maxlength.$invalid}} $invalid【Verification successful】: {{myForm.maxlength.$valid}} $error【Error details】: {{myForm.maxlength.$error}}<br> 4. Pattern matching: {{user.pattern}} $pristine 【Not modified】: {{myForm.pattern.$pristine }} $dirty【Modified】: {{myForm.pattern.$dirty}} $invalid【Verification failed】: {{myForm.pattern.$invalid}} $invalid【Verification successful】: {{myForm.pattern.$invalid}} $error【Error Details】: {{myForm.pattern.$error}}<br> 5. Email: {{user.email}} $pristine 【Not modified】: {{myForm.email.$pristine }} $dirty【Modified】: {{myForm.email.$dirty}} $invalid【Verification failed】: {{myForm.email.$invalid}} $invalid【Verification successful】: {{myForm.email.$valid}} $error【Error Details】: {{myForm.email.$error}}<br> 6. Number: {{user.age}} $pristine 【Not modified】: {{myForm.age.$pristine }} $dirty【Modified】: {{myForm.age.$dirty}} $invalid【Verification failed】: {{myForm.age.$invalid}} $invalid【Verification successful】: {{myForm.age.$valid}} $error【Error details】: {{myForm.age.$error}}<br> 7.URL:{{user.url}} $pristine 【Not modified】: {{myForm.url.$pristine }} $dirty【Modified】: {{myForm.url.$dirty}} $invalid【Verification failed】: {{myForm.url.$invalid}} $invalid【Verification successful】: {{myForm.url.$valid}} $error【Error details】: {{myForm.url.$error}}<br> </div> </body></html><script type="text/javascript"> angular.module('myTest', []) .controller('myController', function($scope) { $scope.submitForm = function(isValid) { if (!isValid) { alert('Verification failed'); } }; } );</script>The effects are as follows:
At the same time, ng has set some css styles for these verification instructions in a targeted manner.
They include:
The code copy is as follows:.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 will be added to this field. You can edit your favorite CSS. You can customize these classes privately to implement specific scenario applications.
However, the default verification instructions may not be able to fully meet our real application scenarios, and the functions of custom verification instructions are also provided by ng.
First, let’s take a 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!#$%&'*+//=?^_`{|}~.-]+@[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 code of the page Html is as follows:
<form role="form" id="custom_form" name="custom_form" novelidate> <div> <label>Multiple email</label> <div> <input multiple-email name="user_email" ng-model="user.email" required placeholder="Custom verification, multiple email addresses, split with ";" or ";" /> Verification passed: {{custom_form.user_email.$valid}} </div> </div> <div> <input ng-disabled="custom_form.$invalid" type="submit" value="submit" /> </div> </form>The code is very simple, and the effect is as follows:
This code is very simple, but involves several important properties of ngModelController. $viewValue
The $viewValue property holds the actual string required to update the view.
$modelValue
$modelValue is held by the data model. $modelValue and $viewValue may be different depending on whether the $parser pipeline operates on it.
$parsers
The value of $parsers is an array composed of functions. When the user interacts with the controller and the $setViewValue() method in the ngModelController is called, the functions in the ngModelController are called one by one when the user interacts with the controller, and the $setViewValue() method in the ngModelController is called one by one in the form of a pipeline. The value read by ngModel from the DOM is passed into the function in $parsers and is processed by the parser in sequence. This is for processing and modifying the values.
Note: The ngModel.$setViewValue() function is used to set the view value in the scope.
The ngModel.$setViewValue() function can accept a parameter.
value (string): The value parameter is the actual value we want to assign to the ngModel instance.
This method updates the local $viewValue on the controller and passes the value to each $parser function (including the validator). When the value is parsed and all functions in the $parser pipeline are called, the value will be assigned to the $modelValue property and passed to the expression provided by the ng-model property in the instruction. Finally, after all steps are completed, all listeners in $viewChangeListeners will be called. Note that calling $setViewValue() alone will not evoke a new digest loop, so if you want to update the directive, you need to manually trigger the digest after setting $viewValue. The $setViewValue() method is suitable for listening for custom events in custom directives (such as using a jQuery plugin with callback functions), we would like to set $viewValue and execute digest loops when the callback is called.
$formatters
The value of $formatters is an array of functions that are called one by one in the form of a pipeline when the value of the data model changes. It has no effect on the $parser pipeline and is used to format and convert values to display in controls with this value bound.
$viewChangeListeners
The value of $viewChangeListeners is an array of functions that are called one by one in the form of a pipeline when the value in the view changes. With $viewChangeListeners, similar behavior can be achieved without using $watch. Since the return value is ignored, these functions do not need to return values.
$error
The $error object holds the validator name that has not passed the verification and the corresponding error information.
$pristine
The value of $pristine is Boolean, which can tell us whether the user has modified the control.
$dirty
The value of $dirty is the opposite of $pristine, which can tell us whether the user has interacted with the control.
$valid
The $valid value tells us whether there are errors in the current control. The value is false when there is an error, and the value is true when there is no error.
$invalid
The $invalid value tells us whether there is at least one error in the current control, and its value is the opposite of $valid.
After learning the basic knowledge points, you need to deeply learn the writing method of custom verification. After ng1.3, the ease of use of verification instructions has been improved.
The above is a detailed explanation of the examples of using AngularJs verification form introduced to you by the editor. I hope it can help you. I will continue to update the relevant knowledge of the angularjs verification form to you in the future. Please pay attention to the Wulin.com website!