Beginning AngularJS

(WallPaper) #1

CHApTer 6 ■ WorkIng WITH ForMS


As we have given our form a name and we have added the novalidation attribute, it is now primed for
validation. Let’s look at validation for the First name and Last name fields. These won’t be too challenging, as the rule
is simply that they are required. The two things that we must do are provide the validation itself and the feedback to
the user, if the validation fails. Examine Listing 6-16.


Listing 6-16. Validating Required Fields and Showing Feedback to the User



Please enter a value for First name



Please enter a value for Last name

The validation is straightforward; we simply add a required attribute to our input elements. With the addition of
this attribute, AngularJS will insist on a value in each of these fields before it will consider the form valid. However, it
insists rather quietly, so it is up to us to tell the user if things went wrong and how to fix them. The approach we apply
here is to use span elements containing the validation error messages. We want to keep these hidden until we have to
show them. We achieve this through the ngShow directive. Let’s focus on the span we added for the First name field.


Please enter a value for First name


As you may recall from our coverage of ngShow in the last chapter, it expects an expression that evaluates to
a Boolean value. Let’s turn to the controller code’s register method in Listing 6-17, as this will show us how the
firstNameInvalid variable is manipulated to trigger the showing and hiding of the validation message.


Listing 6-17. The Registration Method with Some Validation in Place


$scope.register = function () {


$scope.firstNameInvalid = false;
$scope.lastNameInvalid = false;


if(!$scope.registrationForm.firstName.$valid){
$scope.firstNameInvalid = true;
}


if(!$scope.registrationForm.lastName.$valid){
$scope.lastNameInvalid = true;
}


if($scope.registrationForm.$valid){



}


}


When the document first loads, both firstNameInvalid and lastNameInvalid evaluate to false. Consequently,
the ngShow directives will keep the span elements, and therefore the validation messages, hidden. When the user
presses the submit button, we make use of the fact that AngularJS can tell us, on a field-by-field basis, whether or
not an input is valid. In the case of the First name field, which we named firstName, in the form which we named
registrationForm, we can use $scope.registrationForm.firstName.$valid to see if this field is currently valid.
As you might expect, this scope.formName.fieldName.$property format applies to the Last name field too.

Free download pdf