angular - 在Angular 9中的两个选择上验证相同的值
问题描述
我是 Angular 的新手,它实际上是另一个程序员的代码。任何想法或将不胜感激。
我有两个带有三个选项的简单选择,我正在尝试验证它们是否选择了相同的值。
我创建了一个验证器,它检查第二个选择是否与第一个选择具有相同的值。它仅适用于第二个,但是当我更改第一个选择时,验证器不会运行或更新。
代码如下所示:
maxTimeValidator = ( control: FormControl): { [s: string]: boolean } => {
if (!control.value) {
return { required: true };
} else if ( control.value !== this.RiskForm.controls.range_min_time.value ) {
return { differentTimeRange: true, error: true };
}
return {}
}
RiskForm: FormGroup;
submit_error = false;
RiskData = {
id: [null,[]],
range_min_time: [null, [Validators.required]],
range_max_time: [null, [Validators.required,this.maxTimeValidator]],
}
ngOnInit(): void {
// Initialice Form Data
this.RiskForm = this.formBuilder.group(this.RiskData);
}
我尝试创建两个验证函数/相同的问题:更改一个选择时验证器似乎没有运行或更新。
任何建议都会有所帮助,感谢您花时间提供帮助。
解决方案
您需要一个适用于您的表单的验证器。与此类似:
this.registerForm = this.formBuilder.group(
{
firstName: ["", [Validators.required]],
lastName: ["", [Validators.required]],
email: ["", [Validators.required, Validators.email]],
password: ["", [Validators.required, Validators.minLength(6)]],
confirmPassword: ["", Validators.required]
},
{
// Used custom form validator name
validator: ComparePassword("password", "confirmPassword")
}
);
export function ComparePassword(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
return;
}
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
} else {
matchingControl.setErrors(null);
}
};
}
推荐阅读
- mysql - 在 Sequelize 中使用 MySQL FIELD 函数
- python-3.x - 如何将多个.py文件转换成.exe并依次运行?
- python - 在 Django 项目中安装 python 模块
- machine-learning - 为带字幕的食物数据集生成字幕
- raku - 如何在“raku -n”迭代期间获取当前行号?
- python - Python,在图像中查找圆圈
- genexus - 提交到 Genexus 服务器的问题
- c# - 如何从excel复制特定的工作表名称并将其保存到新位置?使用 C#
- javascript - exec() 方法永远不会使用某些正则表达式返回 null
- laravel - Laravel 要求存在间接关系