首页 > 解决方案 > 在 Angular 中为模板驱动的表单应用表单验证

问题描述

我一直在尝试向我的模板驱动表单添加功能,这将使用Angular 文档检查密码是否相等,但似乎在将验证器指令应用于我的表单后,验证甚至不会触发。我的代码:

注册组件.ts

export const matchingPasswordValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
  const password = control.get('password');
  const confirmPassword = control.get('confirmPassword');

  return password.value === confirmPassword.value ? { passwordMatch: true } : null;
};

@Directive({
  selector: '[matchingPassword]',
  providers: [{ provide: NG_VALIDATORS, useExisting: MatchingPasswordValidatorDirective, multi: true }]
})
export class MatchingPasswordValidatorDirective implements Validator {
  validate(control: AbstractControl): ValidationErrors {
    return matchingPasswordValidator(control);
  }
}

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  registerPost: RegisterPost = new RegisterPost();

register.component.html

<form #registerForm="ngForm" matchingPassword>
  <mat-form-field>
    <mat-label>Email</mat-label>
    <input matInput [(ngModel)]="registerPost.email" name="email" #email="ngModel" email required>
    <mat-error *ngIf="email.errors?.email">
      Enter a valid email address
    </mat-error>
  </mat-form-field>

  <mat-form-field>
    <mat-label>Hasło</mat-label>
    <input type="password" matInput [(ngModel)]="registerPost.password" name="password" #password="ngModel"
      required>
  </mat-form-field>

  <mat-form-field>
    <mat-label>Powtórz hasło</mat-label>
    <input type="password" matInput [(ngModel)]="registerPost.confirmPassword" name="confirmPassword"
      #confirmPassword="ngModel" required>
    <mat-error *ngIf="registerForm.errors?.passwordMatch">
      Password does not match.
    </mat-error>
  </mat-form-field>

  <button type="submit" mat-stroked-button color="primary" (click)="!registerForm.valid || register()"
    [loading]="registerClicked">
    Register
  </button>
</form>

标签: angulartypescript

解决方案


推荐阅读