Beginning AngularJS

(WallPaper) #1
CHApTer 6 ■ WorkIng WITH ForMS

Before we look at validation as it applies to specific fields, let’s look at what AngularJS does for us in regard to the
form as a whole. At this form-wide level, AngularJS will give us answers to some important questions: Has the user
started entering any data into the form yet? Is the form as a whole in a valid state? and so on.
Answers to questions such as these are useful in a lot of situations. You will see an example in our registration
form’s validation, as we will determine whether or not to allow the form to submit, based on whether or not the form
is completely valid. We can do such things because AngularJS exposes the answer to these questions via a set of
built-in form properties, as shown in Table 6-2.


Table 6-2. Built-in Form-Level Properties


Property Name Description


$pristine True, if user has not yet interacted with the form


$dirty True, if user has already interacted with the form


$valid True, if all of the containing forms and form elements are valid


$invalid True, if at least one containing form element or form is invalid


We also have access to some very handy CSS style hooks. As the form changes state, such as when it moves from
valid to invalid, AngularJS will dynamically add and remove CSS classes to reflect the current state. You can create your
own set of CSS rules for these classes, thereby styling the form as you see fit for each state. These classes are outlined in
Table 6-3. The style hooks and the built-in form properties will make more sense when we see them in action.


Table 6-3. Dynamically Managed Validation Classes


Class Description


ng-valid Set, if the form is valid


ng-invalid Set, if the form is invalid


ng-pristine Set if the form is pristine


ng-dirty Set, if the form is dirty


ng-submitted Set, if the form was submitted


If you have already worked with the HTML5 specification, you might be pleased to hear that AngularJS respects
attributes such as type and required. It also adds some directives of its own to support forms and form validation
further. Generally, one of the first steps you take when using AngularJS validation is the addition of the novalidate
attribute on your form element, as shown here:



Strange that we should use the novalidate attribute when we actually want to validate. Keep in mind that the
novalidate attribute is not an AngularJS directive; it is a standard HTML attribute that is used to prevent built-in
browser validation. The reason we use it is because we want AngularJS to validate our form. Taking the built-in
browser behavior out of the equation is the best way to remedy the problems that would otherwise occur. We still get
to use the same approach, only with AngularJS running the show instead of the browser.

Free download pdf