Adding validations
Dealing with forms is often a pain for developers because you obviously can't trust the inputs provided by the user. It is either because they are just not paying attention to what you expect in your forms or because they want to break things. Validating inputs incoming from a form is painful in every language, both server and client-side.
Now, the Angular team came up with a rather simple way to validate inputs by defining what is expected from each field right at the form's creation using Validators
. Angular contains the following built-in Validators
that we can use:
required
: Requires a non-empty valueminLength(minLength: number)
: Requires the control value to have a minimum length ofminLength
maxLength(maxLength: number)
: Requires the control value to have a maximum length ofmaxLength
pattern(pattern: string)
: Requires that the control value matches the provided pattern
Adding these built-in validators
to our form is straightforward:
//In AppComponent import { FormGroup...