Angularjs Form Validation Examples _angularjs

Source: Internet
Author: User
Tags validation examples


Common form Validation Directives



1. Required Entry Verification



If a form entry is filled in, just add the HTML5 tag required on the input field element:





Copy Code code as follows:
<input type= "text" required/>





2. Minimum length



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





Copy Code code as follows:
<input type= "Text" ng-minlength= "5"/>





3. Maximum length



Verify that the text length entered in the form is less than or equal to a maximum value and that the directive ng-maxlength= "{number}" is used on the input field:





Copy Code code as follows:
<input type= "text" ng-maxlength= "/>"





4. Pattern matching



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





Copy Code code as follows:
<input type= "text" ng-pattern= "/[a-za-z]/"/>





5. E-Mail



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





Copy Code code as follows:
<input type= "Email" name= "email" ng-model= "User.email"/>





6. Digital



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





Copy Code code as follows:
<input type= "number" name= "Age" ng-model= "User.age"/>





7. URL



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





Copy Code code as follows:
<input type= "url" name= "homepage" ng-model= "User.facebook_url"/>





Here we test the form 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. Minimum 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="20" 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-model="user.email" class="form-control" />
    </div>
   </div>
   <div class="form-group">
    <div class="col-md-4">
     <label for="age">6. Number</label>
</div>
    <div class="col-md-8">
     <input type="number" id="age" name="age" ng-model="user.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>
  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 only when the expression satisfies the validation, the two-way binding is performed in real time. At the same time, we also found that the effect of the chart is as follows:






It doesn't seem to be a problem, but if we migrate it to a team HTML5 validated browsers and test "This example IE9", the problem is that some of the fields are completely unverifiable.






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



Masking browser Default validation behavior for forms



To add a novalidate tag to a FORM element, the question is how do we know which fields in our form are valid, 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 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 to the form in real time.



You can access these properties using the FormName.inputFieldName.property format.



Forms that have not been modified



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





Copy Code code as follows:
Formname.inputfieldname. $pristine;
Modified form





The Boolean property, when and only if the user has actually modified the form. Whether or not the form passes validation:





Copy Code code as follows:
Formname.inputfieldname. $dirty





Validated forms



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





Copy Code code as follows:
Formname.inputfieldname. $valid
Forms that have not been validated
Copy Code code as follows:
Formname.inputfieldname. $invalid





The last two properties are especially useful for displaying or hiding DOM elements. At the same time, they are also useful if you want to set a particular class.



Error



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





Copy Code code as follows:
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 for these kinds of authentication directives, targeted to set some CSS style



They include:





Copy Code code as follows:
. ng-valid {}.ng-invalid {}.ng-pristine {}.ng-dirty {}/* really specific CSS rules applied by angular */.ng-invalid-req uired {}.ng-invalid-minlength {}.ng-valid-max-length {}





They correspond to the specific state of the form input field.



For example, when an entry 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 instructions are not necessarily able to fully meet our real-world scenario, 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!#$%& ' *+\/= ?^_`{|} ~.-]+@[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);
   }
  };
 }]


Page HTML part of the 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 "/>
     authentication through: {{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="/>
   </div>
  </form>


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






This code is simple, but it involves several important attributes of the 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



A $parsers value is an array of functions that, when the user interacts with the controller, and when the $setViewValue () method in the Ngmodelcontroller is invoked, when the user interacts with the controller, and the $setviewvalue () method in Ngmodelcontroller is called in the form of pipelining. Ngmodel values read from the DOM are passed into functions in the $parsers and are then processed by the parser in turn. This is to process and modify values.



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



Ngmodel. $setViewValue () function can accept a parameter.



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



This method updates the local $viewvalue on the controller, and then passes the value to each $parser function (including the validator). When the value is parsed and all functions in the $parser pipelining are called, the values are assigned to the $modelvalue property and passed to the expression provided by the Ng-model property in the instruction. Finally, when all the steps are complete, all the listeners in the$viewChangeListeners are invoked. Note that a separate call to $setviewvalue () does not evoke a new digest loop, so if you want to update the instruction, you need to manually trigger the digest after setting the $viewvalue. $setViewValue () method is appropriate for listening to custom events in custom directives (such as using jquery Plug-ins with callback functions), we would like to set up $viewvalue and perform digest loops on callbacks.



$formatters



The value of the $formatters is an array of functions that are called in a pipelined fashion when the value of the data model changes. It does not affect the $parser pipelining, which is used to format and convert values so that they are displayed in a control that is bound to this value.



$viewChangeListeners



The value of the $viewChangeListeners is an array of functions that are called one at a time when the values in the view change in a pipelined fashion. With $viewchangelisteners, you can implement similar behavior without using $watch. Because the return value is ignored, these functions do not need to return a value.



$error



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



$pristine



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



$dirty



$dirty value is the opposite of $pristine, you can tell us if the user has interacted with the control.



$valid



$valid value tells us if there is an error in the current control. When there is an error value of FALSE, no error value is true.



$invalid



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



After learning the basics of the knowledge point, need to study the custom validation of the writing, has been ng1.3 after the verification instructions to improve the ease of use.



The above is a small set for you to introduce the use of ANGULARJS verification form examples, hope to be able to help everyone, follow-up will continue to give you updated ANGULARJS verify the relevant knowledge of the form, please pay attention to cloud Habitat community website!


Related Article

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.