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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read