As you know AngularJS provides several validation attributes
such as required, minimum length, pattern etc which simplify the form
validation. But showing the validation messages is a big pain (up to version
1.3). We have to write a bunch of ng-if statements to show the proper error
message and this get much more complex than the actual validation.
AngularJS reduces this pain of showing validation messages
using ngMessages directive. The ngMessages internally works like a switch
statement, it will accept an object and based on the values of this object,
ngMessages shows the corresponding message. This can be better demonstrated
with the below example:
Let’s say we have the below javascript object
var messages = {
required: false,
minlength: false,
maxlength: false,
email: true
}
As you see this object contains a set of properties out of
which email is true. Now we will pass this object to the ngMessages directive as
mentioned below
<div ng-messages='vm.messages'>
<div ng-message="required">This field is required</div>
<div ng-message="minlength">This field is too short</div>
<div ng-message="maxlength">This field is too long</div>
<div ng-message="email">This field has an invalid email address</div>
</div>
As expected ngMessages shows the message corresponding to
the email as it’s value is true.
In the actual scenario, instead of our custom object, we
will pass the angular’s error attribute as shown below:
<div ng-messages='loginForm.username.$error>
The ngMessages based on the angular’s error attribute shows
the message. Here is the full code on using the ngMessages directive
<div class="form-group" ng-class="{'has-error': loginForm.username.$invalid
&& vm.isFormSubmitted(loginForm.username) }">
<label for="username" class="col-sm-2 control-label">Username</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="username" ng-model="vm.model.UserName" required autofocus>
<div class="error-messages" ng-messages="loginForm.username.$error" ng-if="vm.isFormSubmitted(loginForm.username)">
<div ng-message="required">Username is required</div>
</div>
</div>
</div>
In my next blog I will go more detail on the above code. For
now let’s assume ngMessage directive acts like a switch statement.
No comments:
Post a Comment