Implementing input validation and error messaging

FormControl is highly customizable. It allows you to set a default initial value, add validators, or listen to changes on blur, change, and submit events, as follows:

example
new FormControl('Bethesda', { updateOn: 'submit' })

We won't be initializing the FormControl with a value, but we need to implement a validator to disallow one character inputs:

  1. Import Validators from @angular/forms:
src/app/city-search/city-search.component.ts
import { FormControl, Validators } from '@angular/forms'
  1. Modify FormControl to add a minimum length validator:
src/app/city-search/city-search.component.ts
search = new FormControl('', [Validators.minLength(2)])
  1. Modify the template to show a validation error message:
src/app/city-search/city-search.component.html
...
<form style="margin-bottom: 32px">
<mat-form-field>
...
<mat-error *ngIf="search.invalid">
Type more than one character to search
</mat-error>
</mat-form-field>
</form>
...
Note the addition of some extra margin to make room for lengthy error messages.

If you are handling different kinds of errors, the hasError syntax in the template can get repetitive. You may want to implement a more scalable solution that can be customized through code, as shown:

example
<mat-error *ngIf="search.invalid">{{getErrorMessage()}}</mat-error>

getErrorMessage() {
return this.search.hasError('minLength') ? 'Type more than one character to search' : '';
}
  1. Modify the search function to not execute a search with invalid input:
src/app/city-search/city-search.component.ts
this.search.valueChanges.pipe(debounceTime(1000)).subscribe((searchValue: string) => {
if (!this.search.invalid) {
...

Instead of doing a simple check to see whether searchValue is defined and not an empty string, we can tap in to the validation engine for a more robust check by calling this.search.invalid.

..................Content has been hidden....................

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