Form validation and custom message

Description

The following code shows how to set form validation and custom message.

Example


<!doctype html>
<html ng-app="myApp" >
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <style>
.error { border: dashed red 1px }
.success { border: dotted  green 1px }
</style>  <!--from  w ww.j  a v a 2  s .  co m-->
  <script>
var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.getCssClasses = function(ngModelContoller) {
    return {
      error: ngModelContoller.$invalid && ngModelContoller.$dirty,
      success: ngModelContoller.$valid && ngModelContoller.$dirty
    };
  };
  
  $scope.showError = function(ngModelController, error) {
    return ngModelController.$error[error];
  };
});
  
  </script>
</head>
<body ng-controller="MainCtrl">
  <form name="userInfoForm">
  <div class="control-group" ng-class="getCssClasses(userInfoForm.email)">
    <label>E-mail</label>
    <input type="email" ng-model="user.email" name="email" required>
    <span ng-show="showError(userInfoForm.email, 'email')" class="help-inline">You must enter a valid email</span>
    <span ng-show="showError(userInfoForm.email, 'required')" class="help-inline">This field is required</span>
  </div>
  <label>Last name</label><br/>
  <input type="text" ng-model="user.lastName" name="lastName" required><br/>
  <label>First name</label><br/>
  <input type="text" ng-model="user.firstName" name="firstName" required><br/>
  <label>Website</label><br/>
  <input type="url" ng-model="user.website" name="website"><br/>
  <label>Description</label><br/>
  <textarea ng-model="user.description" name="description"></textarea><br/>
  <label>Password</label><br/>
  <input type="password" ng-model="user.password" name="password" required><br/>
  <label>Password (repeat)</label><br/>
  <input type="password" ng-model="repeatPassword" name="repeatPassword" required><br/>
  <label>Roles</label><br/>
  <label class="checkbox"><br/>
     <input type="checkbox" ng-model="user.admin" name="admin"> Is Administrator</label><br/>
  <button ng-click="save()" ng-disabled="!canSave()">Save</button>
  </form>

  User Model: <pre>{{user|json}}</pre>
  Form: <pre>{{userInfoForm|json}}</pre>
  
</body>
</html>

Click to view the demo





















Home »
  AngularJS »
    AngularJS Example »




Controller
Directives
Expression
Filter
Form
Inject
Scope
Server
Style
Template
Utilities