Custom form validations

In previous chapters, we learned about forms and implementing form validations. We used the built-in form validations or HTML5 attribute validations. But, in more complex scenarios, we will need to implement custom form validations. These validations differ from application to application. In this section, we will learn about custom form validations. To recap quickly, Angular provides us with various options through which we can implement form validations using the Validators module in Angular forms.

An example of using validators is shown in the following code:

loginForm = new FormGroup({
firstName: new FormControl('',[Validators.required,
Validators.maxLength(15)]),
lastName: new FormControl('',[Validators.required]),
});

In the preceding code, using the Validators module, we are applying validations of required, maxLength, and so on.

Now, let's learn how to create our own custom form validations. First, we will generate a component in which we will implement a form and a few elements so that we can apply our newly created directive:

ng g c customFormValidation

Upon running the preceding command successfully, we should see the following output:

Now that we have generated our component, let's generate a directive in which we will implement custom form validations.

We will implement a custom directive to check the ISBN field.

What is an ISBN? An ISBN is a unique identifier for each book that is ever published.

Here are the conditions that are required for an ISBN number:

  • The ISBN number should be exactly 16 characters
  • Only integers are allowed for ISBNs

Now, using the ng command, we will generate our directive:

ng g directive validISBN

Upon successful execution of the above command we should see the output as shown in the screenshot below

In the valid-isbn.directive.ts file, add the following lines of code:

import { Directive } from '@angular/core';
import { NG_VALIDATORS, ValidationErrors, Validator, FormControl } from '@angular/forms';

@Directive({
selector: '[validISBN]',
providers: [
{ provide: NG_VALIDATORS,
useExisting: ValidISBNDirective, multi: true }
]
})

export class ValidISBNDirective implements Validator {
static validateISBN(control: FormControl): ValidationErrors | null {
if (control.value.length < 13) {
return { isbn: 'ISBN number must be 13 digit long' };
}
if (!control.value.startsWith('Packt')) {
return { isbn: 'Value should start with Packt' };
}
return null;
}

validate(c: FormControl): ValidationErrors | null {
return ValidISBNDirective.validateISBN(c);
}
}

Let's analyze the preceding code snippet in detail. First, using the ng CLI commands, we have generated a directive named validISBN. The Angular CLI will autogenerate the required file, with the basic syntax prepopulated. We are importing the required modules, namely NG_VALIDATORS, ValidationErrors, Validator, and FormControl. We are injecting the required modules as part of our providers. Next up, we have implemented a method named validateISBN, which is taking a parameter of the FormControl type. We are passing our form control field to this method, which will validate whether the value of the form control matches the conditions implemented in the method. Finally, we are invoking the validateISBN method in the method validate. 

Now, we are good to use this custom form validation in any number of places, that is, wherever we need to verify or validate the ISBN number. Let's run the application using the ng serve command. We should see the following output:

So far in this chapter, we have been applying some of them out of box, thinking and learning about how to build our custom directives and custom form validations. We have also learned how easy it is to integrate them into existing, or any new, applications effortlessly. All this can also form parts of single-page applications. Wait. What? Single-page applications? What's that? In the next section, we are going to learn all about single-page applications and build our own.

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

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