gpt4 book ai didi

angular - react 形式 Angular 2的多个自定义验证器

转载 作者:太空狗 更新时间:2023-10-29 17:49:49 26 4
gpt4 key购买 nike

我在响应式(Reactive)表单中有两个自定义验证器,我调用下面的函数在组件构造函数中创建表单:

private createForm(): void {
this.passwordUpdateForm = this.formBuilder.group({
newpassword : [null, Validators.required],
passwordconfirm: [null, Validators.required]
},
{
validator: [PasswordValidation.PasswordMatch, PasswordValidation.PasswordRule] // validation method

});

PasswordValidation 是一个具有如下两个函数的类

    export class PasswordValidation {

public static PasswordMatch(control: AbstractControl) {
let password = control.get('newpassword'); // to get value in input tag
if(password){
let confirmPassword = control.get('passwordconfirm').value; // to get value in input tag
if (password.value !== confirmPassword) {
control.get('passwordconfirm').setErrors({ ['passwordmatch'] : true});
}else {
return null;
}
}
}

public static PasswordRule(control: AbstractControl) {
let password = control.get('newpassword').value; // to get value in input tag
let pattern = new RegExp('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,64}');
if (!pattern.test(password)) {
control.get('newpassword').setErrors({ ['passwordrule'] : true});
}else if (password.toLowerCase() === 'something') {
control.get('newpassword').setErrors({ ['passwordrule'] : true});
}else {
return null;
}
}
}

每个自定义验证器都像这样单独工作

validator: PasswordValidation.PasswordMatch

或者这个

validator: PasswordValidation.PasswordRule

但是像这样在数组中使用它们

validator: [PasswordValidation.PasswordMatch, PasswordValidation.PasswordRule]

得到错误this.validator is not a function并且不起作用,我不知道,请帮助。

最佳答案

最好使用 Validators.compose([]),它接受要在表单组中的特定用户控件上使用的验证器数组。

例如,如果你想为 passwordconfirmnewpassword 控件添加验证器,你可以像下面那样做

private createForm(): void {
this.passwordUpdateForm = this.formBuilder.group({
newpassword : [null, Validators.compose([Validators.required,PasswordValidation.PasswordRule])],
passwordconfirm: [null, Validators.compose([Validators.required, PasswordValidation.PasswordMatch])]
});

底层代码是这样的

group(controlsConfig: {[key: string]: any}, extra: {[key: string]: any} = null): FormGroup {
const controls = this._reduceControls(controlsConfig);
const validator: ValidatorFn = isPresent(extra) ? extra['validator'] : null;
const asyncValidator: AsyncValidatorFn = isPresent(extra) ? extra['asyncValidator'] : null;
return new FormGroup(controls, validator, asyncValidator);
}

可以看到参数validator实际上是一种接口(interface)ValidatorFn,如下所示

interface ValidatorFn { 
(c: AbstractControl): ValidationErrors|null
}

所以你可以看到它可以接受任何具有上述签名的方法。

来源:https://angular.io/api/forms/ValidatorFn

查看此链接了解更多信息:https://toddmotto.com/reactive-formgroup-validation-angular-2

关于angular - react 形式 Angular 2的多个自定义验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46130378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com