angular - 角度中的验证器显示角度中的弃用错误
问题描述
以下是我的验证实用程序功能
import { FormGroup } from '@angular/forms';
// custom validator to check that two fields match
export function MustMatch(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 another validator has already found an error on the matchingControl
return;
}
// set error on matchingControl if validation fails
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
} else {
matchingControl.setErrors(null);
}
}
}
这是组件类
this.userForm = this.formBuilder.group({
id: [0],
userName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(30)]],
password: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(30)]],
confirmPassword: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(30)]],
..
}, {
validator: MustMatch('password', 'confirmPassword') --After adding this i am gtting deprecated error
});
ablove 代码运行良好..但现在 this.formBuilder.group 已被弃用..
请让我有任何替代解决方案..
编辑:
import { AbstractControl } from '@angular/forms';
import { Injectable } from '@angular/core';
@Injectable()
export class ValidationService {
getValidatorErrorMessage(name: string, value?: any) {
const config = {
'required': 'Required',
'email':'Invalid email address',
'invalidPassword': 'This regex can be used ',
'mustMatch': `Passwords must match`,
};
return config[name];
}
password(control: AbstractControl) {
if (control.value.match(/^(?=[^\d_].*?\d)\w(\w|[!@#$%]){7,20}/)) {
return null;
} else {
return { 'invalidPassword': true };
}
}
//can i move mustmatch function here?
}
这是我的验证服务..是否可以在验证服务中进行验证..
解决方案
您的验证器函数需要返回ValidationErrors | null
export function MustMatch(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 another validator has already found an error on the matchingControl
return null;
}
// set error on matchingControl if validation fails
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
return { mustMatch: true };
} else {
matchingControl.setErrors(null);
return null;
}
}
}
推荐阅读
- angular - 角度材料切换未定义未命中
- xcode - XCODE 11、SWIFT 5。画线、框等
- vuepress - VuePress:确定是在预渲染上下文中运行还是在浏览器中运行
- java - 在 IOS 中打开 websocket 时出错(CFNetwork SSLHandshake failed (-9807))
- reactjs - 尝试导入错误:“Test1”未从“Test_components”导出
- java - 如何在一个循环中使用 PdfWriter 和 PdfCopy 在现有 PDF 页面中添加内容
- git - 在不丢失代码的情况下更新 Git 子模块
- java - Flyway使用java类对sql文件进行排序
- java - 即使对于不同的请求 grpc,方法也会继续运行并发送相同的信息
- jupyter-notebook - 在 JupyterLab 中打开 .ipynb 时出错 - “关闭而不保存?”