我正在尝试使用自定义验证来验证表单.出于某种原因,我必须构建一个可以更改电子邮件或设置新密码的表单.出于这个原因,我不能使用Validators.required,因为密码字段只有在被触摸时才需要.
我的问题是,当解决输入验证时,表单仍然无效.
我做了一个plnkr来证明我的问题:http://plnkr.co/edit/obF4gC5RHkXOOlCEsIuH?p = preview
ngOnInit(): void {
this.emailField = new FormControl('mail@mail.com', Validators.email);
this.pw1 = new FormControl('', [this.passwordAreEqualValidator, Validators.minLength(2)]);
this.pw2 = new FormControl('', this.passwordAreEqualValidator);
this.pwOld = new FormControl('', this.notEmptyIfNewIsTouchedValidator);
this.form = this.formBuilder.group({
pw1: this.pw1,
pw2: this.pw2,
emailField: this.emailField,
pwOld: this.pwOld
});
}
notEmptyIfNewIsTouchedValidator(control: FormControl) : ValidationErrors | null {
if (control.dirty) {
if (control.value === '') {
return {
oldPasswordEmpty: true
}
}
const parent = control.parent,
pw1 = parent.get('pw1'),
pw2 = parent.get('pw2');
// this will trigger nothing …Run Code Online (Sandbox Code Playgroud)