I want to perform form validation. If the field is "dirty".
An error should be displayed if there is nothing in the password field.
If the passwords do not match, an error should also be displayed.
Can you explain to me what is wrong with my code? I have already created a code example:
Minimal Reproducible Stackblitz
Full Code:
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import {
AbstractControl,
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import { FormsModule } from '@angular/forms';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
@Component({
selector: 'app-root',
standalone: true,
imports: [
ReactiveFormsModule,
MatInputModule,
MatFormFieldModule,
MatCheckboxModule,
MatButtonModule,
FormsModule,
],
template: `
<form [formGroup]="registerForm">
<mat-form-field>
<mat-label>Password</mat-label>
<input matInput formControlName="password" type="password">
@if (registerForm.get('password').hasError('required') && registerForm.get('password').dirty) {
<mat-error>Password is required</mat-error> }
</mat-form-field>
<mat-form-field>
<mat-label>Confirm Password</mat-label>
<input matInput formControlName="confirmPassword" type="password"> @if (registerForm.errors?.['mismatch'] && registerForm.dirty) {
<mat-error>Password does not match</mat-error> }
</mat-form-field>
<button mat-raised-button color="primary " type="submit" [disabled]="!registerForm.valid">Sign up</button>
</form>
`,
})
export class App {
name = 'Angular';
registerForm: FormGroup;
constructor() {
this.registerForm = new FormGroup(
{
password: new FormControl('', [
Validators.required,
Validators.minLength(6),
]),
confirmPassword: new FormControl('', [Validators.required]),
},
{ validators: this.passwordMatchValidator }
);
}
private passwordMatchValidator(control: AbstractControl) {
return control.get('password')?.value ===
control.get('confirmPassword')?.value
? null
: { mismatch: true };
}
}
bootstrapApplication(App, {
providers: [provideAnimationsAsync()],
});
I use Angular 17 and Angular Material.