How to Add Validator to FormControl After Control is Created in Angular ?
Last Updated :
12 Apr, 2024
Adding a validator to a form typically refers to the process of defining rules or conditions that suggest whether the data entered into the form fields is valid or not. Initially, the form can be submitted without any validation. However, after adding a validation rule, submission is only allowed if the input meets the specified criteria.

Prerequisites:
Steps to create angular project
Step 1: Set Up Angular Project
Install Angular CLI: If you haven't already, install the Angular CLI globally by running the following command:
npm install -g @angular/cli
Step 2: Create Angular Project: Create a new Angular project using Angular CLI:
ng new dynamic-validation-form-angular
Navigate to Project Directory: Enter the project directory:
cd dynamic-validation-form-angular
Generate Component: Generate a new component for the dynamic validation form:
ng generate component dynamic-validation-form
Project Structure:

Dependencies:
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Changing file structure:
- Remove unnecessary files, keep the project clean with required files as shown in project structure
- Create dynamic-validation-form folder inside app with 3 files as shown above with the following code.
- create app.module.ts inside app folder with following code
- create environment.ts and main.ts file inside src with following code and replace content of src/index.html
HTML
<!-- dynamic-validation-form.component.html -->
<div class="form-container">
<h1 class="form-title">Dynamic Validation Form</h1>
<form (submit)="handleSubmit($event)" class="form">
<div class="form-group">
<label class="form-label">Email:</label>
<input
type="email"
[(ngModel)]="emailValue"
(change)="handleEmailChange($event)"
class="form-control"
[required]="isEmailRequired"
/>
<div *ngIf="isEmailRequired" class="error">{{ emailError }}</div>
<button
type="button"
(click)="handleAddEmailValidator()"
class="btn add-validator-btn"
>
Add Email Validator
</button>
</div>
<div class="form-group">
<label class="form-label">Password:</label>
<input
type="password"
[(ngModel)]="passwordValue"
(change)="handlePasswordChange($event)"
class="form-control"
[required]="isPasswordRequired"
/>
<div *ngIf="isPasswordRequired" class="error">{{ passwordError }}</div>
<button
type="button"
(click)="handleAddPasswordValidator()"
class="btn add-validator-btn"
>
Add Password Validator
</button>
</div>
<button type="submit" class="btn submit-btn">Submit</button>
</form>
</div>
HTML
<!-- src/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic Validation Form Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<app-dynamic-validation-form></app-dynamic-validation-form>
</body>
</html>
CSS
/*dynamic-validation-form.component.css*/
.form-container {
width: 100%;
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f9f9f9;
}
.form-title {
text-align: center;
margin-bottom: 20px;
}
.form {
display: flex;
flex-direction: column;
}
.form-group {
margin-bottom: 15px;
}
.form-label {
font-weight: bold;
}
.form-control {
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
}
.error {
color: red;
margin-top: 5px;
}
.btn {
padding: 10px;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.btn:hover {
background-color: #007bff;
color: #fff;
}
.add-validator-btn {
margin-right: 10px;
}
.submit-btn {
background-color: #28a745;
color: #fff;
}
.submit-btn:hover {
background-color: #218838;
}
JavaScript
//dynamic-validation-form.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-dynamic-validation-form',
templateUrl: './dynamic-validation-form.component.html',
styleUrls: ['./dynamic-validation-form.component.css'],
})
export class DynamicValidationFormComponent {
emailValue: string = '';
passwordValue: string = '';
isEmailRequired: boolean = false;
isPasswordRequired: boolean = false;
emailError: string = '';
passwordError: string = '';
handleEmailChange(event: any): void {
this.emailValue = event.target.value;
}
handlePasswordChange(event: any): void {
this.passwordValue = event.target.value;
}
handleAddEmailValidator(): void {
this.isEmailRequired = true;
}
handleAddPasswordValidator(): void {
this.isPasswordRequired = true;
}
handleSubmit(event: any): void {
event.preventDefault();
if (this.isEmailRequired &&
!this.isValidEmail(this.emailValue)) {
this.emailError = 'Please enter a valid email address.';
return;
}
if (this.isPasswordRequired &&
!this.isValidPassword(this.passwordValue)) {
this.passwordError =
'Password must be at least 8 characters
long and contain at least one uppercase
letter, one lowercase letter, one number,
and one special character.';
return;
}
this.emailError = '';
this.passwordError = '';
alert('Form submitted successfully!');
}
isValidEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
isValidPassword(password: string): boolean {
const passwordRegex =
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)
(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
return passwordRegex.test(password);
}
}
JavaScript
//src/environment.ts
export const environment = {
production: false,
apiUrl: 'http://localhost:3000/api'
// Add other environment variables as needed
};
JavaScript
//src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { DynamicValidationFormComponent }
from './dynamic-validation-form/dynamic-validation-form.component';
@NgModule({
declarations: [
DynamicValidationFormComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [DynamicValidationFormComponent]
})
export class AppModule { }
JavaScript
// src/main.ts
import { enableProdMode } from '@angular/core';
import { platformBrowser } from '@angular/platform-browser';
import { AppModule } from './app/app.module';
import { environment } from './environment';
if (environment.production) {
enableProdMode();
}
platformBrowser().bootstrapModule(AppModule)
.then(module => { })
.catch(err => console.error(err));
Run the Angular Application using the following command.
ng serve
Output:

Similar Reads
How to check whether a form or a control is valid or not in Angular 10 ? In this article, we are going to check whether a form is touched or not in Angular 10. The valid property is used to report that the control or the form is valid or not. Syntax: form.valid Return Value: boolean: the boolean value to check whether a form is valid or not. NgModule: Module used by the
1 min read
How to clear form after submission in Angular 2? In Angular 2, they are two types of forms: Template-driven forms. Reactive forms. In template-driven forms, most of the content will be populated in .html file.In Reactive forms, most of the functionalities and content will be performed in .ts file. The main advantage of reactive forms is, we can cr
2 min read
How to disable a form control in Angular ? In this article, we are going to see how to disable a form control in Angular 10. We will use AbstractControl disabled property to disable a form control element. Syntax: <formelement disabled></formelement> Return Value: boolean: returns boolean stating whether the element is disabled o
2 min read
How to perform custom validation in Angular forms? Angular's built-in form controls provide a set of predefined validators for common validation such as required fields, email format, and minimum/maximum values. However, there may be cases where you need to implement custom validation logic specific to your application's requirements. Angular offers
4 min read
How to check whether a form or a control is touched or not in Angular 10 ? In this article, we are going to check whether a form is touched or not in Angular 10. The touched property is used to report that the control or the form is touched or not. Syntax: form.touched Return Value: boolean: the boolean value to check whether a form is touched or not. NgModule: Module used
1 min read