在Angular中实现重复输入字段验证可以使用自定义验证器。以下是一个示例代码,演示了如何在Angular中使用自定义验证器来验证重复输入字段:
import { FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';
export const matchingFieldsValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
const fieldName = control.get('fieldName')?.value;
const matchingFieldName = control.get('matchingFieldName')?.value;
if (fieldName && matchingFieldName && fieldName !== matchingFieldName) {
return { matchingFields: true };
}
return null;
};
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { matchingFieldsValidator } from './matching-fields.validator';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
form: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit(): void {
this.form = this.formBuilder.group({
fieldName: ['', Validators.required],
matchingFieldName: ['', Validators.required]
}, { validator: matchingFieldsValidator });
}
// 其他表单相关的方法
}
在上面的代码中,我们首先在FormGroup中使用{ validator: matchingFieldsValidator }
将自定义验证器应用于整个表单组。然后,在模板中使用form.hasError('matchingFields')
来检查是否存在匹配字段错误,并显示相应的错误消息。
这样,当用户输入的字段值不匹配时,表单将被认为是无效的,并显示相应的错误消息。