我正在修改自定义验证器内的控制值,并且由于循环验证的明显问题,我不需要触发验证。
@Directive({
selector: '[myValidator]',
standalone: true,
providers: [
{
provide: NG_VALIDATORS,
useExisting: MyValidatorDirective,
multi: true,
},
],
})
export class MyValidatorDirective implements Validator {
validate(control: AbstractControl): ValidationErrors | null {
return myValidatorFn(
this.phoneNumberValidationService,
this.countryCodeControl,
this.defaultCountryCode
)(control);
}
}
export function myValidatorFn(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (control.value) {
if (control.value.indexOf("something") > 0) {
return { myError: { value: true } };
}
control.setValue(control.value.replace("other", ""));// Some random value change, here is when the validation is called again
}
return null;
};
}
我结束了更改此代码的
setValue
行(我删除了所有验证器,设置了值,然后再次添加):
const validatorFn = this.validator;
if (validatorFn != null) {
this.clearValidators();
}
this.setValue(value, options);
if (validatorFn != null) {
this.addValidators(validatorFn);
}