Angularjs form verification and status and error handling

Source: Internet
Author: User
Tags error handling regular expression valid

How can AngularJS benefit us when processing forms and especially validating forms and inputs of various states:


<html ng-app = "notesApp">
<head> <title> Notes App </ title> </ head>
<body ng-controller = "MainCtrl as ctrl">
  <form ng-submit = "ctrl.submit ()" name = "myForm">
    <input type = "text"
       ng-model = "ctrl.user.username"
       required
       ng-minlength = "4">
    <input type = "password"
       ng-model = "ctrl.user.password"
       required>
    <input type = "submit"
       value = "Submit"
       ng-disabled = "myForm. $ invalid">
  </ form>
<script src = "http://riafan.com/libs/angular.js"> </ script>
<script type = "text / javascript">
  angular.module ('notesApp', [])
    .controller ('MainCtrl', [function () {
      var self = this;
      self.submit = function () {
        console.log ('User clicked submit with', self.user);
      };
    }]);
</ script>
</ body>
</ html>


In the following example, we modify the previous example to add some validation. Especially if the user does not fill in all required fields, we want to disable the submit button. How do we do this?

    We give the form the name myForm for future reference.
    We use HTML5 validation tags to add a required attribute to each input field.
    We add the ng-minlength validator to force the minimum length of username input text to be 4 characters.
    We click the Submit button and add an ng-disabled instruction. Disables the element if the condition is true.
    We use a form to expose a form controller with the current state. In this case, the button is disabled if $ invalid for the form named myForm is true.

When you use forms (name them), AngularJS creates a FormController to hold the current state of the form and some helper methods. As we used myForm in the previous example, you can access the FormController form by the form name. The properties that are exposed as status and kept up-to-date with data binding are shown in the following table.

Table 4-1. Form status in AngularJS
Form status Description
$ invalid AngularJS sets this state when any validation (required, ng-minlength, etc.) identifies any field of the form as invalid
$ valid is the opposite of $ invalid, setting all form validations to currently evaluate to the correct state
$ pristine All forms in AngularJS start from this state. This allows you to find out if the user has started typing and modifying any form elements. Possible usage: Disable the reset button in the original state of the form.
$ dirty is the opposite of $ pristine. Ie the user made some changes (he can revert, but the $ dirty flag is already set).
$ error contains a reference to a control or form that failed validation. We will discuss this part further in the following sections.

Each state mentioned in the table is a Boolean value that can be used to conditionally hide, show, disable, or enable HTML user interface elements. When the user enters or modifies the form, as long as the ng-model and form name are used, the status value will be updated synchronously.


AngularJS form error handling

We've covered multiple types of validation that can be tested at the form level, but what about individual fields? In the previous example, we ensured that the input fields are required fields and the minimum length of username is 4. What else can we do? Table 4-2 contains some of the built-in validations for AngularJS.

Table 4-2. AngularJS built-in validators
Validator description
required As discussed earlier, this ensures that fields are required and fields are marked as invalid until they are filled.
ng-required is different from required, which indicates that the field is also required. The ng-required directive allows us to mark the input field as required based on the controller Boolean condition.
ng-minlength This command can set the minimum length of the input text value
ng-maxlength This command can set the minimum length of the text input value
ng-pattern As part of this directive, the validity of text input can be checked against the specified regular expression pattern.
type = ”email” Text input with built-in email verification.
type = ”number” Text input with quantity validation. There can also be additional properties for minimum and maximum.
type = ”date” displays an HTML date picker if supported by the browser. Otherwise, it defaults to a text input. ng-model
Bind to a date object. The expected date format is yyyy-mm-dd (for example, 2009-10-24).
type = ”url” URL text input with input validation.
In addition, we can write our own validator, which we will address in a later chapter.



Show error message

What can we do with these validators? Of course it can be used to check the validity of the form and disable the save or update button accordingly. But we also need to tell the user what went wrong and how to fix it. AngularJS provides two solutions to solve this problem:

    The model accurately reflects what the form error is, and we can use it to display more friendly error messages.
    CSS classes that are automatically added and removed from each field allow us to highlight form errors.

First let's take a look at how to display specific error messages based on the error object, see the following example:


<html ng-app = "notesApp">
<head> <title> Notes App </ title> </ head>
<body ng-controller = "MainCtrl as ctrl">
  <form ng-submit = "ctrl.submit ()" name = "myForm">
    <input type = "text"
       name = "uname"
       ng-model = "ctrl.user.username"
       required
       ng-minlength = "4">
    <span ng-show = "myForm.uname. $ error.required">
      This is a required field
    </ span>
    <span ng-show = "myForm.uname. $ error.minlength">
      Minimum length required is 4
    </ span>
    <span ng-show = "myForm.uname. $ invalid">
      This field is invalid
    </ span>
    <input type = "password"
       name = "pwd"
       ng-model = "ctrl.user.password"
       required>
    <span ng-show = "myForm.pwd. $ error.required">
      This is a required field
    </ span>
    <input type = "submit"
       value = "Submit"
       ng-disabled = "myForm. $ invalid">
  </ form>
<script src = "http://riafan.com/libs/angular.js"> </ script>
<script type = "text / javascript">
  angular.module ('notesApp', [])
    .controller ('MainCtrl', [function () {
      var self = this;
      self.submit = function () {
        console.log ('User clicked submit with', self.user);
      };
    }]);
</ script>
</ body>
</ html>


No changes have been made to the controller in this example. Instead, we can just focus on the HTML of the form. Let's see what the form changes:

    First, we added the name attribute to the two input fields that need to be verified, the username text is uname, and the pwd password text is pwd.
    Then use AngularJS form binding to find errors for each form field. When we added the name attribute to any input form, we actually created a model with an error status specifically for it.
    So for the username field, we can check if it is filled in by visiting myForm.uname $ error.required. Also for ng-minlength, the field should be myForm.uname. $ Error.minlength. For passwords, we verify that the field is filled in by myForm.pwd. $ Error.required.
    Similar to forms, we also access the input status through myForm.uname. $ Invalid. All other form states we described earlier ($ valid, $ pristine, and $ dirty) also apply to the myForm.uname object.

With the model, an error message is now displayed only when some type of error is triggered. Each validator in the above table exposes the corresponding key of the error object. Therefore, we can find it and display a specific error message to the user. Is it necessary to display the field for the username? Then when the user starts typing, the minimum length of the input is displayed, and finally a message is displayed when the input exceeds the maximum length. All these types of conditional information can be displayed using the AngularJS validator.



Styling forms and states

We have seen the forms (inputs) of various states: $ dirty, $ valid, etc. We saw how to display specific error messages and disable buttons based on these conditions, but what if we want to use the user interface and CSS to emphasize certain input fields or form states? One option is to use the form and input state with the ng-class directive, such as adding the dirty class when myForm. $ Dirty is true. But AngularJS offers an easier option.

For each of the states we described above, AngularJS adds and removes CSS classes for form and input elements, as shown in Table 4-3.



Table 4-3. Form status CSS classes
Form status applied CSS class
$ invalid ng-invalid
$ valid ng-valid
$ pristine ng-pristine
$ dirty ng-dirty


Similarly, for each validator added to the input field, we can use a similarly named CSS class, as shown in Table 4-4 below.



Table 4-4. Input Status CSS Classes
Input Status Applied CSS Class
$ invalid ng-invalid
$ valid ng-valid
$ pristine ng-pristine
$ dirty ng-dirty
required ng-valid-required or ng-invalid-required
min ng-valid-min or ng-invalid-min
max ng-valid-max or ng-invalid-max
pattern ng-valid-pattern or ng-invalid-pattern
url ng-valid-url or ng-invalid-url
email ng-valid-email or ng-invalid-email
date ng-valid-date or ng-invalid-date
number ng-valid-number or ng-invalid-number


In addition to the basic input state, AngularJS also needs the name (number, maximum length, mode, etc.) of the validator. Depending on whether the particular validator meets the requirements, add the ng-valid-validator_name or ng-invalid-validator_name class accordingly.

Let's look at an example where the input can be emphasized in different ways:

In this example, we retain the child's existing validator functionality, although we remove specific error messages. Instead, what we are trying to do is use CSS classes to mark the required fields. This is the completed example:

    When the fields are filled in correctly, the input box turns green. This is done by setting the background color when the CSS class ng-valid is applied to our input field.
    If we want to display a dark red background when the user starts typing, then undo it. That is, we want to set the background to red and mark the required fields, but only after the user has modified the fields. So we set the background color to red, if applied

CSS class ng-dirty (identifies that the user has modified) ng-invalid-minlength (identifies that the user has not entered a sufficient number of characters).

Similarly, if the field is required but not dirty, you can add a CSS class to display it in red *. Using a combination of these CSS classes (forms and input states) from scratch, you can easily use styles to present all relevant, actionable user interfaces to the user.

 
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.