Validation with the input and select components

Angular provides three different ways of building forms in our applications:

  • Template-driven approach: This approach allows us to build forms with very little to no application code required
  • Model-driven (or reactive) approach using low-level APIs: In this approach, we create our forms as testable without a DOM being required
  • Model-driven with a higher level API: This approach uses a higher level API called FormBuilder.

PrimeNG created most of the input and select components with model-driven form support. Because of this, all input and select components are eligible for validation.

Let's take an example of a registration form with firstname, lastname, password, address, phone, and gender fields with validation support. PrimeNG components are backed by a model-driven API with FormBuilder, which groups all of the form controls to create a registration form, as shown here:

this.registrationform = this.formBuilder.group({
'firstname': new FormControl('', Validators.required),
'lastname': new FormControl('', Validators.required),
'password': new FormControl('',
Validators.compose([Validators.required,
Validators.minLength(8)])),
'address': new FormControl(''),
'phone': new FormControl(''),
'gender': new FormControl('', Validators.required)
});

HTML, however, contains the form element with a formGroup binding with the registration form. The form will wrap with the list of controls and validation conditions to display messages:

<form [formGroup]="registrationform" (ngSubmit)="onSubmit(registrationform.value)">
...
</form>

A registration form with invalid input would result in an error messages, as shown in the following snapshot:

PrimeNG components provide validations through template-driven forms, as well as model-driven forms. The flexibility is given to the user on what kind of validation needs to be provided.

The complete demo application with instructions is available on GitHub at
https://github.com/ova2/angular-development-with-primeng/tree/master/chapter3/validation.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.44.182