Open In App

How to Add Validator to FormControl After Control is Created in Angular ?

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.

Screenshot-2024-03-29-231959

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:

Screenshot-2024-04-04-150430

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:

<!-- 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>
<!-- 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>
/*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;
}
//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);
    }
}
//src/environment.ts

export const environment = {
    production: false,
    apiUrl: 'http://localhost:3000/api'
    // Add other environment variables as needed
};
//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 { }
// 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:

vv

Article Tags :