You can create custom validators for your application's specific requirements.
typescript
// custom-validators.ts
import { AbstractControl, ValidationErrors } from '@angular/forms';
export class CustomValidators {
// No whitespace validator
static noWhitespace(control: AbstractControl): ValidationErrors | null {
const isWhitespace = (control.value || '').trim().length === 0;
return isWhitespace ? { whitespace: true } : null;
}
// Password match validator
static passwordMatch(control: AbstractControl): ValidationErrors | null {
const password = control.get('password');
const confirmPassword = control.get('confirmPassword');
if (!password || !confirmPassword) return null;
return password.value === confirmPassword.value
? null
: { passwordMismatch: true };
}
}
// Usage in component
this.userForm = this.fb.group({
username: ['', [Validators.required, CustomValidators.noWhitespace]],
password: ['', Validators.required],
confirmPassword: ['']
}, { validators: CustomValidators.passwordMatch });You should see
(The custom validation rules work and return their specific errors)