Validating user input in HTML forms can be a tedious task. In this new series, we’ll look at how Angular can help us implement painless form validation.
First, it’s essential to know that Angular relies primarily on native browser validation features that use modern HTML properties. For instance, if a form field has to be filled out, you can mark it as required using the required
HTML attribute:
If the user input has to match a specific format, you can specify such format using the pattern
attribute, which uses a regular expression syntax – here, a 5-digit number
Other available HTML validation attributes are min
, max
, minlength
, maxlength
. You can also set the input type to something more specific than text
, such as email
or tel
for additional validation and capabilities. Here is the list of all possible input types.
Once you have specified your validation rules using such attributes, Angular is going to toggle some CSS classes on the corresponding HTML elements automatically: ng-valid
when the entered value is valid, and ng-invalid
when the entered value is invalid.
This means that all we have to do to provide visual feedback to the user is implementing such classes in our CSS stylesheets:
The above CSS classes result in the following styling of form inputs:
If we want to fine-tune the rendering of our form based on whether the user has already typed something or not, there are additional classes added by Angular for such purposes:
ng-pristine
: true
when the user has not changed the element value
ng-dirty
: opposite of pristine — true
when the user has altered the element value
ng-touched
: true
when the user has put focus on the element (say clicked on it) and then removed the focus from the element (clicked away from it)
ng-untouched
: Opposite of touched — means the user hasn’t put focus on the element or hasn’t removed that focus yet.
Using combinations of these classes is powerful. For instance, here is how we could add the error styles only once the user has “touched” an input:
Which results in the following default rendering:
And then once the user has typed something and removed the focus from the element:
You can try a few live examples using the code from this Stackblitz repo. Tomorrow, we’ll see how to do more than just CSS styling using those validation properties.