In this exercise we add validation and error messages to prevent adding contacts without a name.
We don't have any validations in our new form. Let's use the built-in required
and minlength
validator to have some validation and display appropriate error messages.
- Add the
novalidate
HTML5 attribute to the form, so the browser's default validation is turned off - Disable
ContactCreatorComponent
's save button using the forms validity state - Set
<mat-input-container>
'sdividerColor
property to either "warn" or "primary" depending on if the field has errors or not - Add
required
andminlength="3"
validator to the input control - Add an
<mat-hint>
element to into the<mat-input-container>
if the field is notvalid
and notpristine
. Here's a snippet:
<input matInput #name="ngModel" ...>
<mat-hint align="end" *ngIf="!name.valid && !name.pristine">
<!-- Error messages go here -->
</mat-hint>
- Display error message inside the
<mat-hint>
element usingngIf
for bothrequired
andminlength
- Add information about
minlength
error in error message (actualLength
)
- Refactor
ContactsEditorComponent
to also use template-driven forms and the same validation (keep in mind that one button is of typesubmit
whereas the other one is of typebutton
.
Go to Forms Lab #3: Add Custom eMail Validator