AngularJS Tutorial - AngularJS Form








AngularJS makes it easy to handle client-side form validations.

To use form validations, we must ensure that the form has a name associated with it.

All input fields can have some basic validations, like minimum length, maximum length, etc. These are all available on the new HTML5 form attributes.

We can use the novalidate flag on the form element to prevent the validating.

Let's look at all the validation options we have that we can place on an input field:

To mark a required field, we add the HTML5 tag, required, to the input field:

<input type="text" required />

To set the minimum length for form input, we add the AngularJS directive ng-minlength="{number}" to the input field:

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

To set maximum length for a form input, we can add the AngularJS directive ng-maxlength="{number}":

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

To ensure that an input matches a regex, we can use ng-pattern="/PATTERN/":

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

To validate an email address, we set the input type to email:

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

To validate an input field has a number, we set the input type to number:

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

To validate that an input represents a URL, set the input type to url:

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




Example

The following code is revised from http://jsbin.com/ePomUnI/5/edit.

<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>
<style id="jsbin-css">
input.ng-invalid {<!--  w  ww. ja  v  a 2s  .c o  m-->
  border: 1px solid red;
}

input.ng-valid {
  border: 1px solid green;
}
</style>
</head>
<body>
  
<form name="signup_form" novalidate ng-submit="signupForm()">
    <div class="row">
      <div class="large-12 columns">
        <label>Your name</label>
        <input type="text" 
            placeholder="Name" 
            name="name" 
            ng-model="signup.name" 
            ng-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>
      
    <div class="row">          
      <div class="large-12 columns">
        <label>Your email</label>
        <input type="email" 
          placeholder="Email" 
          name="email" 
          ng-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>
      
    <div class="large-12 columns">
      <label>Username</label>
        <input  type="text" 
                placeholder="Desired username" 
                name="username" 
                ng-model="signup.username" 
                ng-minlength=3 
                ng-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>  

    <button type="submit" ng-disabled="signup_form.$invalid" class="button radius">Submit</button>
</form>
<script id="jsbin-javascript">
angular.module('myApp', [])
.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);
        });
      });
    }
  };
}]);
</script>
</body>
</html>

The code above is rendered as follows:





Form properties

We can access form properties in the format of

formName.inputFieldName.property

These properties enable us to react to the form.

Unmodified Form property is a boolean that tells us whether the user has modified the form. It is true if the user hasn't touched the form, and false if they have:

formName.inputFieldName.$pristine;

Modified Form property is a boolean that tells us if the user has modified the form.

formName.inputFieldName.$dirty

Valid Form property is a boolean that tells us whether the form is valid.

formName.inputFieldName.$valid

Invalid Form property is a boolean that tells us whether or not the form is invalid.

formName.inputFieldName.$invalid

The $error object contains all of the validations on a particular form and a record of whether they are valid or invalid.

formName.inputfieldName.$error

Form validation class

When AngularJS is handling a form, it adds classes to the form based on the current state.

These classes are:

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

When a field is invalid, the .ng-invalid class will be applied to the field.

For example we can set the class as follows:

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