AngularJS - Simple Form Validation

  Client-side form validation is one of the coolest features in AngularJS. AngularJS form validation lets you write modern HTML5 forms that are interactive and responsive from the start.

  In AngularJS, there are many form validation directives. Here, we'll talk about some of the most popular directives, and then we'll discuss how to write custom validations.

<form name="form">
  <label name="email">Your email</label>
  <input type="email" name="email" ng-model="email" placeholder="Email Address" />
</form>

  AngularJS makes it easy to handle client-side form validation without extra effort. While we can't keep our web application secure with client-side validation alone, they provide good instant feedback on the form.

  To use form validation, we first have to make sure the form tag has a name attribute, like in the example above. do you understand? Great!

  All input fields can perform some basic validation, such as minimum length, maximum length, etc. These are attributes validation of HTML5 tags.

  It is usually necessary to add the novalidate attribute to the form tag, which will disable the browser's own validation function and use the validation provided by AngularJS.

  Let's see what validations we can set on the input:

1. Required

  To verify that a character has been entered, just add required to the label:

<input type="text" required />

2. Minimum length

  Validate that the input is at least {number} characters, using the AngularJS directive ng-minlength="{number}":

<input type="text" ng-minlength=5 />

3. Maximum length

  To verify that the input characters are less than or equal to {number} characters, use the ng-maxlength="{number}" of the AngularJS directive:

<input type="text" ng-maxlength=20 />

4. Regular matching

  To make sure the input matches a regular expression, use the AngularJS directive ng-pattern="/PATTERN/":

<input type="text" ng-pattern="/a-zA-Z/" />

5.Email

  To verify that the input character is an email address, just set the input's type property to email, like this:

<input type="email" name="email" ng-model="user.email" />

6. Numbers

  To verify that the input character is a number, just set the input's type property to number, like this:

<input type="number" name="email" ng-model="user.age" />

7.Url

  To verify that the input character is a URL address, just set the input type attribute to url, like this:

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

8. Custom Validation

  AngularJS makes it easy to add custom validation using directives. For example, we want to verify that our username is available (not repeated in the database). To do this, we'll implement a directive that triggers an Ajax request when the input character changes:

var app = angular.module('validationExample', []);

app.directive('ensureUnique', ['$http', function($http) {
  return {
    require: 'ngModel',
    link: function(scope, ele, attrs, c) {
      scope.$watch(attrs.ngModel, function() {
        $http({
          method: 'POST',
          url: '/api/check/' + attrs.ensureUnique,
          data: {'field': attrs.ensureUnique}
        }).success(function(data, status, headers, cfg) {
          c.$setValidity('unique', data.isUnique);
        }).error(function(data, status, headers, cfg) {
          c.$setValidity('unique', false);
        });
      });
    }
  }
}]);

9. Validate the form state

  AngularJS stores the results of DOM validation in the $scope object. This allows us to make some responses in real time. The properties provided to us are:

  Note that this is the format of this property: formName.inputFieldName.property

a. Unmodified form

  Boolean property that indicates whether the user has modified the form. If it is true, it means that it has not been modified; false means it has been modified:

formName.inputFieldName.$pristine;

b. Modified form

  Boolean property if and only if the user has actually modified the form. Regardless of whether the form passes validation:

formName.inputFieldName.$dirty

c. Validated form

  Boolean property that indicates whether the form passed validation. It will be true if the form is currently validated:

formName.inputFieldName.$valid

d. Forms that do not pass validation

  Boolean property that indicates whether the form passed validation. It will be true if the form is not currently validated:

formName.inputFieldName.$invalid

  The last two properties are especially useful when used to show or hide DOM elements. At the same time, they are also very useful if you want to set a specific class.

e. Error

  Another useful property is the $error object provided to us by AngularJS. This object contains whether each validation of the input is valid or invalid (a collection). To access this property, use the following syntax:

formName.inputfieldName.$error

  If validation fails, this property will be true, and if it is false, the value will pass validation.

10. Innocent styles

  When AngularJS handles form validation, it will add some specific class attributes depending on the state of the validation. These classes are named with similar properties that we can inspect.

  These classes are:

.ng-pristine {}
.ng-dirty {}
.ng-valid {}
.ng-invalid {}

  These classes correspond to the results of their corresponding validation objects.

  When a field is invalid, .ng-invalid will be applied to the field. We can style these classes with css:

input.ng-invalid {
  border: 1px solid red;
}
input.ng-valid {
  border: 1px solid green;
}

11. Put it all together

  Let's write a registration form. This application form will include the person's name, their email, and the desired username.

  Let's define a form form:

<form name="signup_form" novalidate ng-submit="signupForm()">
  <fieldset>
    <legend>Signup</legend>

    <button type="submit" class="button radius">Submit</button>
  </fieldset>
</form>

  The name of this form is signup_form and when we click submit we will call the signupForm() method.

  Now, let's add the User's Name property:

<div class="row">
  <div class="large-12 columns">
    <label>Your name</label>
    <input type="text"
        placeholder="Name"
        name="name"
        model = "signup.name"
        of-minlength = 3
        ng-maxlength=20 required />
  </div>
</div>

  First I want to state that I use Foundation as my css framework, so you will see its related syntax in the code. We add an input field named name, and the object is bound to the signup.name object of the $scope object (via ng-model).

  We also set up several validations. These validations are: We must have a name that is 3 or more characters long. And the maximum length is limited to 20 characters (21 or more characters will be invalid). Finally, we set the name should be required.

  Let's use a property to control whether to show or hide the error list if the form is invalid. We'll also use the $dirty property to make sure the error message doesn't show up when the user doesn't enter a character:

<div class="row">
  <div class="large-12 columns">
    <label>Your name</label>
    <input type="text"
        placeholder="Name"
        name="name"
        model = "signup.name"
        of-minlength = 3
        ng-maxlength=20 required />
   <div class="error"
        ng-show="signup_form.name.$dirty && signup_form.name.$invalid">
    <small class="error"
        ng-show="signup_form.name.$error.required">
        Your name is required.
    </small>
    <small class="error"
            ng-show="signup_form.name.$error.minlength">
            Your name is required to be at least 3 characters
    </small>
    <small class="error"
            ng-show="signup_form.name.$error.maxlength">
            Your name cannot be longer than 20 characters
    </small>
  </div>
  </div>
</div>

  Before, it could only tell us if our input was valid when the input changed. This time, we'll see error messages for those that don't pass validation.

  Let's take a look at the next verification, an email:

<div class="row">          
  <div class="large-12 columns">
    <label>Your email</label>
    <input type="email"
      placeholder="Email"
      name="email"
      model = "signup.email"
      ng-minlength = 3 ng-maxlength = 20 required />
    <div class="error"
         ng-show="signup_form.email.$dirty && signup_form.email.$invalid">
      <small class="error"
             ng-show="signup_form.email.$error.required">
             Your email is required.
      </small>
      <small class="error"
             ng-show="signup_form.email.$error.minlength">
              Your email is required to be at least 3 characters
      </small>
      <small class="error"
             ng-show="signup_form.email.$error.email">
             That is not a valid email. Please input a valid email.
      </small>
      <small class="error"
             ng-show="signup_form.email.$error.maxlength">
              Your email cannot be longer than 20 characters
      </small>
    </div>
  </div>
</div>

  This time (including the entire form), we write the email field. Note that we set the input's type property to email and added the $error.email error message. This is AngularJS based email validation (using HTML5 attributes).

  Finally, let's look at our last input box, the username:

<div class="large-12 columns">
  <label>Username</label>
    <input  type="text"
            placeholder="Desired username"
            name="username"
            ng-model="signup.username"
            of-minlength = 3
            of-maxlength = 20
            ensure-unique="username" required />
  <div class="error" ng-show="signup_form.username.$dirty && signup_form.username.$invalid">
    <small class="error" ng-show="signup_form.username.$error.required">Please input a username</small>
    <small class="error" ng-show="signup_form.username.$error.minlength">Your username is required to be at least 3 characters</small>
    <small class="error" ng-show="signup_form.username.$error.maxlength">Your username cannot be longer than 20 characters</small>
    <small class="error" ng-show="signup_form.username.$error.unique">That username is taken, please try another</small>
  </div>
</div>

  In our last field, we use the custom validation we wrote earlier. The AngularJS directive used for this custom validation:

app.directive('ensureUnique', ['$http', function($http) {
  return {
    require: 'ngModel',
    link: function(scope, ele, attrs, c) {
      scope.$watch(attrs.ngModel, function() {
        $http({
          method: 'POST',
          url: '/api/check/' + attrs.ensureUnique,
          data: {'field': attrs.ensureUnique}
        }).success(function(data, status, headers, cfg) {
          c.$setValidity('unique', data.isUnique);
        }).error(function(data, status, headers, cfg) {
          c.$setValidity('unique', false);
        });
      });
    }
  }
}]);

  When the form input is valid, it will send a POST api/check/username request to the server to check if the username is available. Now, obviously, since we're only talking about front-end code here, we're not writing tests for the back-end, although that's easy enough.

  Update: Based on the comments in the comments, I've added a server timeout check. To see the full source code, click here.

  Finally, we add the submit button, and we can use the ng-disabled directive to control disabling and enabling of the button depending on whether the validation is valid:

<button type="submit" ng-disabled="signup_form.$invalid" class="button radius">Submit</button>

  As we said above, the attribute $invalid whether the form is valid provides us with convenience.

12. Practical application

  While instant validation is great, it alerts the user right away, but when they are typing long text that would pass validation, they often see an error midway through the input. You can handle this better. Let's look at both when the user clicks submit, or when they move the cursor away from the input box.

a. After clicking submit, the verification information will be displayed

  To display validation when the user tries to submit the form, you can control the display of errors by setting a 'submitted' value in the scope and checking that value.

  For example, let's look at the first example where the error is only displayed when the submit form is clicked. Using the ng-show directive to control the display, we can add a check to see if the submit button has been clicked:

<form name="signup_form" novalidate ng-submit="signupForm()">
  <fieldset>
    <legend>Signup</legend>
    <div class="row">
      <div class="large-12 columns">
        <label>Your name</label>
        <input type="text"
            placeholder="Name"
            name="name"
            model = "signup.name"
            of-minlength = 3
            ng-maxlength=20 required />
       <div class="error"
            ng-show="signup_form.name.$dirty && signup_form.name.$invalid && signup_form.submitted">
        <small class="error"
            ng-show="signup_form.name.$error.required">
            Your name is required.
        </small>
        <small class="error"
                ng-show="signup_form.name.$error.minlength">
                Your name is required to be at least 3 characters
        </small>
        <small class="error"
                ng-show="signup_form.name.$error.maxlength">
                Your name cannot be longer than 20 characters
        </small>
      </div>
      </div>
    </div>
    <button type="submit" class="button radius">Submit</button>
  </fieldset>
</form>

  Now, that error message div will only show when signup_form.submitted is true. We can implement this signupForm method like this:

app.controller('signupController', ['$scope', function($scope) {
  $scope.submitted = false;
  $scope.signupForm = function() {
    if ($scope.signup_form.$valid) {
      // Submit as normal
    } else {
      $scope.signup_form.submitted = true;
    }
  }
}]);

  Now, when a user tries to submit a form and has an invalid element at the same time, you can catch it and tell them the reason for the error.

b. Validation error when going to focus at that time

  If you want to keep the error validation real-time, you can display the error message when the user leaves the input box. To do this, we can add a directive that will add a new variable.

  We use the ngFocus directive, which looks like:

app.directive('ngFocus', [function() {
  var FOCUS_CLASS = "ng-focused";
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, ctrl) {
      ctrl.$focused = false;
      element.bind('focus', function(evt) {
        element.addClass(FOCUS_CLASS);
        scope.$apply(function() {ctrl.$focused = true;});
      }).bind('blur', function(evt) {
        element.removeClass(FOCUS_CLASS);
        scope.$apply(function() {ctrl.$focused = false;});
      });
    }
  }
}]);

  To use ngFocus, we simply add this directive to the input element, like this:

<input ng-class="{error: signup_form.name.$dirty && signup_form.name.$invalid}" type="text" placeholder="Name" name="name" ng-model="signup.name" ng-minlength=3 ng-maxlength=20 required ng-focus />

  After adding the ngFocus directive, the corresponding operations will be registered in the blur and focus events of the input box. When the focus is on the input box, it will add a class (ng-focused), and the $focused property of the input box will also become true. Therefore, you can personalize the error message to be displayed depending on whether the focus is on or not. E.g:

<div class="error" ng-show="signup_form.name.$dirty && signup_form.name.$invalid && !signup_form.name.$focused">

13 Summary

a. If you don't want to display an error message when the page loads, you can do this:

<div class="error" ng-show="addPsaForm.RINM.$dirty ">  
        <span class="error" ng-show="addPsaForm.RINM.$error.required">不能为空</span>  
       <span class="error" ng-show="addPsaForm.RINM.$error.maxlength">长度越界:1-128</span>  
</div>

  Determine whether the form has been modified by the user to show or hide the prompt information.

b. When the form validation fails, the submit button can be disabled from clicking.

<input type="submit" value="提交" ng-disabled="addPsaForm.$invalid"/>  

 

Article source: http://www.cnblogs.com/woshinidezhu/p/Form-validation-with-AngularJS.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326474962&siteId=291194637