Mastering Web Application

(Rick Simeone) #1
Chapter 5

Showing validation errors

We can show error messages for inputs and for the form as a whole if something is
not valid. In the template:


<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')" ...>
You must enter a valid email
</span>

<span ng-show="showError(userInfoForm.email, 'required')" ...>
This field is required
</span>
</div>
...
</form>

In the controller:


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];
};
});

Try it at http://bit.ly/XwLUFZ.


This example shows the e-mail input from our User Form. We are using Twitter
Bootstrap CSS to style the form, hence the control-group and inline-help CSS
classes. We have also created two helper functions in the controller.

Free download pdf