# Prerequisites: Install Angular CLI globally if not already installed
npm install -g @angular/cli
# Create a new Angular project
ng new reactive-forms-demo --routing=false --style=css --standalone=false
cd reactive-forms-demo
# Install dependencies (none extra needed)
ng serve
Here's a complete Angular application demonstrating complex reactive forms with:
- Nested
FormGroups (personal info, address).
- Dynamic
FormArrays (hobbies, skills with sub-controls).
- Built-in validators (required, email, minLength, pattern).
- Custom synchronous validators:
mustMatch: Ensures confirm password matches password.
strongPassword: Requires 8+ chars, uppercase, lowercase, number, special char.
validZip: US ZIP code format (5 digits).
forbiddenEmailDomains: Blocks specific domains (e.g., test.com).
- Custom asynchronous validator:
usernameAvailable: Simulates API check for username availability (with 1s delay).
- Form validation with cross-field logic.
- Dynamic add/remove controls.
- Reactive form submission and value logging.
Replace the contents of the following files in src/app/:
1. src/app/validators.ts (Custom Validators)
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
import { Observable, of, timer } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
// Synchronous: Password must match
export function mustMatch(controlName: string, matchingControlName: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const controlValue = control.get(controlName)?.value;
const matchingValue = control.get(matchingControlName)?.value;
return controlValue === matchingValue || matchingValue === null || matchingValue === '' ? null : { mustMatch: true };
};
}
// Synchronous: Strong password (8+ chars, uppercase, lowercase, number, special)
export function strongPassword(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (!value) return null;
const hasUpperCase = /[A-Z]/.test(value);
const hasLowerCase = /[a-z]/.test(value);
const hasNumbers = /\d/.test(value);
const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(value);
const isLongEnough = value.length >= 8;
return !hasUpperCase || !hasLowerCase || !hasNumbers || !hasSpecial || !isLongEnough
? { strongPassword: true }
: null;
};
}
// Synchronous: Valid US ZIP (5 digits)
export function validZip(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
return value && !/^\d{5}$/.test(value) ? { validZip: true } : null;
};
}
// Synchronous: Forbidden email domains
export function forbiddenEmailDomains(forbiddenDomains: string[]): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const email = control.value;
if (!email) return null;
const domain = email.split('@')[1]?.toLowerCase();
return forbiddenDomains.includes(domain || '') ? { forbiddenEmailDomain: true } : null;
};
}
// Asynchronous: Username availability (mock API)
export function usernameAvailable(): ValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
return timer(1000).pipe( // Simulate 1s delay
switchMap(() => {
const takenUsernames = ['admin', 'user', 'test']; // Mock taken usernames
return of(takenUsernames.includes(control.value) ? { usernameTaken: true } : null);
})
);
};
}
2. src/app/user.service.ts (Mock Service for Async Validator - Optional, but used in validators.ts above)
// Not strictly needed since mock is inline, but for realism
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class UserService {
checkUsername(username: string): Observable<boolean> {
const taken = ['admin', 'user', 'test'];
return of(!taken.includes(username)).pipe(delay(1000));
}
}
3. src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, ReactiveFormsModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
4. src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import {
mustMatch,
strongPassword,
validZip,
forbiddenEmailDomains,
usernameAvailable
} from './validators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
registrationForm!: FormGroup;
submitted = false;
forbiddenDomains = ['test.com', 'example.com'];
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.registrationForm = this.fb.group({
// Personal Info Group
personal: this.fb.group({
username: ['', [Validators.required, Validators.minLength(3)], [usernameAvailable()]],
email: ['', [Validators.required, Validators.email], [forbiddenEmailDomains(this.forbiddenDomains)]],
password: ['', [Validators.required, strongPassword()]],
confirmPassword: ['', Validators.required]
}, { validators: mustMatch('password', 'confirmPassword') }),
// Address Group
address: this.fb.group({
street: ['', Validators.required],
city: ['', Validators.required],
zip: ['', [Validators.required, validZip()]]
}),
// Hobbies Array
hobbies: this.fb.array([]),
// Skills Array (complex: each skill has name + level)
skills: this.fb.array([
this.createSkill()
])
});
}
// Getter for easy access
get f() { return this.registrationForm.controls; }
get personal() { return this.registrationForm.get('personal') as FormGroup; }
get address() { return this.registrationForm.get('address') as FormGroup; }
get hobbies() { return this.registrationForm.get('hobbies') as FormArray; }
get skills() { return this.registrationForm.get('skills') as FormArray; }
createSkill(): FormGroup {
return this.fb.group({
name: ['', Validators.required],
level: [1, [Validators.required, Validators.min(1), Validators.max(10)]]
});
}
addHobby(): void {
this.hobbies.push(this.fb.control('', Validators.required));
}
removeHobby(index: number): void {
this.hobbies.removeAt(index);
}
addSkill(): void {
this.skills.push(this.createSkill());
}
removeSkill(index: number): void {
this.skills.removeAt(index);
}
onSubmit(): void {
this.submitted = true;
if (this.registrationForm.valid) {
console.log('Form Submitted!', JSON.stringify(this.registrationForm.value, null, 2));
alert('Registration successful! Check console for form data.');
}
}
onReset(): void {
this.submitted = false;
this.registrationForm.reset();
this.hobbies.clear();
while (this.skills.length > 1) {
this.skills.removeAt(0);
}
this.skills.at(0)?.patchValue({ name: '', level: 1 });
}
}
5. src/app/app.component.html
<div class="container mt-4">
<h2>User Registration Form (Reactive Forms Demo)</h2>
<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
<!-- Personal Info -->
<div formGroupName="personal" class="card mb-4">
<div class="card-header">Personal Information</div>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Username</label>
<input type="text" formControlName="username" class="form-control" [class.is-invalid]="submitted && f.personal?.get('username')?.invalid">
<div *ngIf="submitted && f.personal?.get('username')?.invalid" class="invalid-feedback">
<div *ngIf="f.personal?.get('username')?.errors?.['required']">Username is required.</div>
<div *ngIf="f.personal?.get('username')?.errors?.['minlength']">Min 3 chars.</div>
<div *ngIf="f.personal?.get('username')?.errors?.['usernameTaken']" class="text-danger">Username taken!</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Email</label>
<input type="email" formControlName="email" class="form-control" [class.is-invalid]="submitted && f.personal?.get('email')?.invalid">
<div *ngIf="submitted && f.personal?.get('email')?.invalid" class="invalid-feedback">
<div *ngIf="f.personal?.get('email')?.errors?.['required']">Email is required.</div>
<div *ngIf="f.personal?.get('email')?.errors?.['email']">Invalid email.</div>
<div *ngIf="f.personal?.get('email')?.errors?.['forbiddenEmailDomain']">Forbidden domain!</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Password</label>
<input type="password" formControlName="password" class="form-control" [class.is-invalid]="submitted && f.personal?.get('password')?.invalid">
<div *ngIf="submitted && f.personal?.get('password')?.invalid" class="invalid-feedback">
Password must be 8+ chars with uppercase, lowercase, number, special char.
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Confirm Password</label>
<input type="password" formControlName="confirmPassword" class="form-control" [class.is-invalid]="submitted && f.personal?.get('confirmPassword')?.invalid">
<div *ngIf="submitted && personal?.errors?.['mustMatch']" class="invalid-feedback">Passwords must match!</div>
</div>
</div>
</div>
</div>
</div>
<!-- Address -->
<div formGroupName="address" class="card mb-4">
<div class="card-header">Address</div>
<div class="card-body">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Street</label>
<input type="text" formControlName="street" class="form-control" [class.is-invalid]="submitted && address?.get('street')?.invalid">
<div *ngIf="submitted && address?.get('street')?.invalid" class="invalid-feedback">Street required.</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>City</label>
<input type="text" formControlName="city" class="form-control" [class.is-invalid]="submitted && address?.get('city')?.invalid">
<div *ngIf="submitted && address?.get('city')?.invalid" class="invalid-feedback">City required.</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>ZIP Code</label>
<input type="text" formControlName="zip" class="form-control" [class.is-invalid]="submitted && address?.get('zip')?.invalid">
<div *ngIf="submitted && address?.get('zip')?.errors?.['validZip']" class="invalid-feedback">5-digit ZIP required.</div>
</div>
</div>
</div>
</div>
</div>
<!-- Hobbies -->
<div class="card mb-4">
<div class="card-header">Hobbies <button type="button" (click)="addHobby()" class="btn btn-sm btn-primary ml-2">Add Hobby</button></div>
<div formArrayName="hobbies" class="card-body">
<div *ngFor="let hobby of hobbies.controls; let i = index" [formControlName]="i" class="input-group mb-2">
<input type="text" class="form-control" placeholder="Enter hobby">
<div class="input-group-append">
<button type="button" (click)="removeHobby(i)" class="btn btn-danger">Remove</button>
</div>
</div>
</div>
</div>
<!-- Skills -->
<div class="card mb-4">
<div class="card-header">Skills <button type="button" (click)="addSkill()" class="btn btn-sm btn-primary ml-2">Add Skill</button></div>
<div formArrayName="skills" class="card-body">
<div *ngFor="let skill of skills.controls; let i = index" [formGroupName]="i" class="row mb-3">
<div class="col-md-8">
<label>Skill Name</label>
<input type="text" formControlName="name" class="form-control">
</div>
<div class="col-md-3">
<label>Level (1-10)</label>
<input type="number" formControlName="level" class="form-control" min="1" max="10">
</div>
<div class="col-md-1">
<button type="button" (click)="removeSkill(i)" class="btn btn-danger mt-4">Remove</button>
</div>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<button type="submit" class="btn btn-success">Register</button>
<button type="button" (click)="onReset()" class="btn btn-secondary ml-2">Reset</button>
</div>
</div>
</form>
<!-- Debug: Form Value -->
<div class="mt-4">
<h5>Form Status: {{ registrationForm.status | titlecase }}</h5>
<pre>{{ registrationForm.value | json }}</pre>
</div>
</div>
6. src/app/app.component.css (Bootstrap-like Styling)
/* Basic Bootstrap styles for demo */
.container { max-width: 800px; }
.card { box-shadow: 0 2px 4px rgba(0,0,0,.1); }
.card-header { background: #f8f9fa; font-weight: bold; }
.form-group { margin-bottom: 1rem; }
.form-control.is-invalid { border-color: #dc3545; }
.invalid-feedback { display: block; width: 100%; margin-top: 0.25rem; font-size: 0.875em; color: #dc3545; }
.ml-2 { margin-left: 0.5rem; }
.mt-4 { margin-top: 1.5rem; }
.btn { padding: 0.375rem 0.75rem; border: none; border-radius: 0.25rem; cursor: pointer; }
.btn-primary { background: #007bff; color: white; }
.btn-success { background: #28a745; color: white; }
.btn-danger { background: #dc3545; color: white; }
.btn-secondary { background: #6c757d; color: white; }
.input-group-append { margin-left: 0; }
pre { background: #f8f9fa; padding: 1rem; border-radius: 0.25rem; overflow-x: auto; }
Run the App
- Run
ng serve in the project directory.
- Open
http://localhost:4200.
- Test:
- Try invalid ZIP (not 5 digits).
- Password without special chars.
- Mismatched passwords.
- Email
@test.com.
- Username "admin" (wait 1s for async error).
- Add/remove hobbies/skills.
- Submit valid form → Check console.
This app showcases advanced reactive forms: nesting, arrays, custom sync/async validators, dynamic controls, and real-time validation. Fully functional and extensible! 🚀