our

Latest Blogs

Custom validation in Template-Driven Angular Forms

iFour Team -June 10, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  •  
  •  
  •  
Custom validation in Template-Driven Angular Forms

Template-Driven Angular Form

In Template-driven forms we specify logic, validations, controls, etc, in the HTML code. Template-driven forms are appropriate for simple scenarios, it uses two-way data binding using the [(NgModel)] syntax.

Validator in angular

A validator in Angular is a function that will return null if the control is valid or an error if the control invalid.

If the form field is valid in step with the validator logic then a validator function will return, otherwise, it returns false.

Built-in validators

Angular provides some built-in validators such as required, minlength, maxlength, pattern, etc. But when there is a need for some customized logic for the validation to use anyw here in the application, then we can simply use Angular Directives to customize the validator.

Implementing Template-Driven Form

To implement Template-Driven Form we need to import FormsModule in app.module.ts file.

app.module.ts:

Building a custom validator

We can create custom validators according to our requirements.

The Dependency Injection Token are type, a string or an instance of InjectionToken.

In this application, we have created a pass-match validator that ensures that the password field characters and characters in the confirm password field are the same.

For Example, we would like to inject the instance of the EmployeeService, we will use the EmployeeService as the token as shown below

providers :[{ provide: EmployeeService, useClass: EmployeeService }]

The EmployeeService is then injected into the component file by using the following code.

We will create a directive and name it pass-match by executing the following command.

ng g directive pass-match

In this file, we find an array named providers in @Directive decorator. In this array, the first element is provide: NG_VALIDATORS which is a special token that registers the validator to the collection of already existing validators (in our case these are required and minlength). All the built-in validators are already added in NG_VALIDATORS token and we are adding our custom validator in this.

The next element is useExisting in which we provide the name of the directive.

The last element is multi: true. It is a special kind of provider that will return multiple dependencies as a list of a given token. Using multi providers a new value will be added to the NG_VALIDATORS token.

The PassMatchDirective class implements Validator Interface. We will override the Validate() method of this interface. This validate() method requires an object of FormControl.

We will create a separate file pass-match validator. In this file, we will create PassMatch() method that contains the actual customized validation logic. This method will return null if both the passwords match otherwise the validator returns error.

pass-match.validator.ts:

Now, we will create a registration form with fields for firstname, lastname, DOB, email id, password, and confirm password. Apply built-in validator required to make sure that all the fields are filled when a user hits the register button. We have also applied minlength validator in the password field to make sure that the password entered by the user is the minimum length of 6 characters.

We will apply the directive PassMatch to this template in the confirm-password field.

app.component.html:

On successful registration, we will give a success alert which will contain the information filled by the user in all the fields. The users can register successfully when they have filled in information according to the validators otherwise error message will be displayed under the field there is a violation of the validator. This code is written in onSubmit() method in the app.component.ts file.

app.component.ts:

One-stop-oplossing voor AngularJS-ontwikkeling ? Your Search ends here.

When we run the application by executing the ng serve --open command we get the following output.

output 1

figure 1-output 1

When the user clicks on the register button without filling in any field it will give the following error message as we have applied the required validator in all the fields.

Output 2

Figure 2-Output 2

output 3

Figure 3-Output 3

When the characters of both the password field and confirm-password field do not match, that will give the following error message as we have built a custom validator “Pass-Match” that ensures that all the characters in both the fields are the same.

Output 4

Figure 4-Output 4

On the successful registration, this alert message will be shown to the user including the information the user has passed in the form

Output 5

Figure 5-Output 5

Conclusion

oWe can apply some common built-in validators in the form to ensure that the information gets filled in the form fields are valid. We can create custom validators according to the business logic along with the built-in validators. Custom validator returns null if the information is valid according to the logic otherwise it returns an error message.

Work with us

Well do everything we can to make our next best project!

Our Insights

Check out our most recent blogs

An in-depth guide on Angular Dependency Providers
An in-depth guide on Angular Dependency Providers

What is Angular? Angular is a frontend development framework used for building single-page client applications using HTML and Typescript. It is written in Typescript. What...

A simple guide to Build Angular Reactive Templates with Ngif and Async Pipe
A simple guide to Build Angular Reactive Templates with Ngif and Async Pipe

Angular Templates seamlessly help to expedite the development process with flawless assistance of components and other specific elements. These are dynamic and renders according...

A simple guide on AOT Compilation in Angular
A simple guide on AOT Compilation in Angular

What is a Compiler? A compiler is nothing but a part of code that converts one programming language to another. If we talk about some simple programming languages like C, C++,...

Our Partners

Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo
Logo

Work With Us

Well do everything we can to make our next best project!