我想从自定义验证创建两个或更多方法来检查恢复密码,但我不能在表单构建器中获得两个以上的参数,该消息始终显示:
使用给定的配置地图构造一个新的{@link FormGroup}。额外参数映射的有效键是validator和asyncValidator。
预计有1-2个参数,但得到3个。
一种方法有效,但第二种方法不起作用
方法:
static MatchPreviousPassword(AC: AbstractControl) {
const previousPassword = 'guide';
const confirmPreviousPassword = AC.get('previousPassword').value;
if (previousPassword !== confirmPreviousPassword) {
console.log('false');
AC.get('previousPassword').setErrors({ MatchPassword: true });
} else {
console.log('true');
return null;
}
}
static MatchPassword(AC: AbstractControl) {
const password = AC.get('newPassword').value;
const confirmPassword = AC.get('confirmPassword').value;
if (password !== confirmPassword) {
console.log('false');
AC.get('confirmPassword').setErrors({ MatchPassword: true });
} else {
console.log('true');
return null;
}
}
表单构建器:
buildForm() {
const min_char = 4;
const max_char = 10;
this.passwordForm = this.fb.group({
'previousPassword': [this.objAuthentication.password,
Validators.compose([ Validators.required, Validators.minLength(min_char), Validators.maxLength(max_char),])],
'newPassword': [this.objAuthentication.password,
Validators.compose([Validators.minLength(min_char), Validators.maxLength(max_char), Validators.required])],
'confirmPassword': [this.objAuthentication.password, Validators.required]
},
{
validator: UserPasswordResetComponent.MatchPassword << Trouble here!!!
});
}
答案 0 :(得分:0)
这就是我在项目中的表现(使用被动方法):
import {Component, OnInit} from '@angular/core';
import {FormGroup, FormControl, Validators} from "@angular/forms";
@Component({
selector: 'register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit{
registerForm: FormGroup;
ngOnInit() {
this.registerForm = new FormGroup({
'fullName': new FormControl(null, [Validators.minLength(2), Validators.required]),
'position': new FormControl(null, [Validators.required]),
'email': new FormControl(null, [Validators.email, Validators.required]),
'password': new FormControl(null, [Validators.minLength(6), Validators.required]),
'passwordRepeat': new FormControl(null, [Validators.minLength(6), Validators.required]),
'image': new FormControl([], []),
},
//two custom validators here:
[passwordMatch, myImageValidation]);
}
}
// password validator
export function passwordMatch(control: FormGroup) : {[key: string]: boolean}
{
return control.value.password !== control.value.passwordRepeat ? {'passwordMatch': true} : null;
}
// image validator just for example
export function myImageValidation(control: FormGroup) : {[key: string]: boolean}
{
return control.value.image !== null ? {'myImageValidation': true} : null;
}
希望它对你有用。如果您有任何疑问,请与我们联系。祝你好运。