我已经创建了一个自定义验证器,我想检查密码确认是否有效:
static cannotContainSpace(control: AbstractControl) : ValidationErrors | null{
console.log('----- control', control.get('password'));
console.log('----- control', control.get('passwordConfirmation'));
if((control.value as string).indexOf(' ') >= 0){
return {cannotContainSpace : true}
}
return null;
}
你能告诉我为什么在这些控制台日志中我总是得到空值吗?我的表单由reactive form
构建,看起来像:
form = new FormGroup({
login: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('',
[
Validators.required,
Validators.minLength(3),
PasswordValidators.cannotContainSpace
]),
passwordConfirmation: new FormControl('', [Validators.required])
});
答案 0 :(得分:0)
因为您已经拥有密码控制权。因此,寻找control.get()
没有意义。如果您使用control.value
,则会看到password
控件的当前值。并且passwordConfirmation
没有作为验证者的值没有在该控件下注册。
答案 1 :(得分:0)
我将错误本地化 - 它看起来应该是:
form = new FormGroup({
login: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('',
[
Validators.required,
Validators.minLength(3),
PasswordValidators.cannotContainSpace
]),
passwordConfirmation: new FormControl('', [Validators.required])
}, PasswordValidators.cannotContainSpace);
我们需要在表单中添加validator
,而不是在FormControl
String