我想执行表格验证.如果字段是"肮脏的".
-
如果密码字段中没有内容,则应显示错误.
-
如果密码不匹配,也应该显示错误.
你能给我解释一下我的代码有什么问题吗?我已经创建了一个代码示例:
Minimal Reproducible Stackblitz
完整代码:
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()],
});
我使用Angular 17和Angular Metal.