Write your first custom validator.
The email field is optional, which is okay. However, we're able to enter whatever we want. Let's make sure the entered value is an actual email address.
- Create a new directive using angular-cli
ng generate directive email-validator
- Import
FormControl
from@angular/forms
in that file - Write a stand-alone function
validateEmail(c: FormControl)
that uses a regular expression to test the value of the given control.
- The Regexp is:
const VALID_EMAIL = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
- Use
.test()
on the regexp to check if control value is an email address - In case of an error, return an object that looks like this:
{
validateEmail: {
valid: false
}
}
- Change
EmailValidator
directive's selector to[trmValidateEmail][ngModel]
- Add the new validator to the
NG_VALIDATORS
multi provider - Add
EmailValidator
to the ngModuledeclarations
inapp.modules.ts
(probably already one by angular cli) - Apply
trmValidateEmail
directive on email input control - Set
<mat-input-container>
'sdividerColor
property to either "warn" or "primary" depending on if the field has errors or not - Add an
<mat-hint>
element to into the<mat-input-container>
if the field is notvalid
and notpristine
. Here's a snippet:
<input matInput #email="ngModel" ...>
<mat-hint align="end" *ngIf="!email.valid && !email.pristine">
<!-- Error messages go here -->
</mat-hint>
- Apply the same validator in the
ContactsEditorComponent
as well
Go to Forms Lab #4