This is a quick example of how to setup form validation in Angular 10 using Reactive Forms. The example is a simple registration form with pretty standard fields for title, first name, last name, date of birth, email, password, confirm password and an accept terms and conditions checkbox. All fields are required including the checkbox, the dob must be a valid date, the password field must have a min length of 6 and the email address must be in a valid format. There’s also a custom MustMatch validator which is used to validate that the confirm password and password fields match.

I’ve setup the form to validate on submit rather than as soon as each field is changed, this is implemented with a submitted property in the app component that is set to true when the form is submitted for the first time, and reset to false if the cancel button is clicked.

Styling of the example is all done with Bootstrap 4.5 CSS, for more info about Bootstrap see https://getbootstrap.com/docs/4.5/getting-started/introduction/.

Here it is in action:

(See on StackBlitz at https://stackblitz.com/edit/angular-10-reactive-form-validation-example)

App Component

The app component contains our example sign up form which creates the form fields and validators using an Angular FormBuilder to create an instance of a FormGroup that is stored in the registerForm property. The registerForm is then bound to the <form> element in the app template below using the [formGroup] directive.

The component contains a convenience getter property f to make it easier to access form controls from the template. So for example you can access the confirmPassword field in the template using f.confirmPassword instead of registerForm.controls.confirmPassword.

#angular 10 #reactive forms #registerform #formgroup #formbuilder

Angular 10 - Reactive Forms Validation Example
59.45 GEEK