溫馨提示×

Angular中怎么自定義驗證器

小億
93
2024-06-04 17:45:29
欄目: 編程語言

在Angular中自定義驗證器可以通過創(chuàng)建一個函數(shù),并將其應用到表單控件上來實現(xiàn)。下面是一個簡單的例子:

首先,創(chuàng)建一個自定義驗證器函數(shù):

import { AbstractControl } from '@angular/forms';

export function customValidator(control: AbstractControl): {[key: string]: any} | null {
  const valid = control.value === 'example';
  return valid ? null : { custom: true };
}

然后,在組件中將這個驗證器函數(shù)應用到表單控件上:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { customValidator } from './custom-validator';

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html'
})
export class MyFormComponent {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      myControl: ['', [Validators.required, customValidator]]
    });
  }
}

最后,在模板文件中顯示驗證錯誤信息:

<form [formGroup]="myForm">
  <input formControlName="myControl">
  <div *ngIf="myForm.controls.myControl.hasError('custom')">
    This field must be 'example'
  </div>
</form>

通過以上步驟,你就可以在Angular中自定義驗證器并進行驗證了。

0