I have build a Custom Validator for my Form, which returns expected ValidationErrors object.
ValidateDirectory(clientId: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const ret: ValidationErrors = { isValidDirectory: true };
if (control.value == null || control.value === '') {
return ret;
}
this.service.getList(clientId, control.value).subscribe((res) => {
if (res.technicalRetCode !== 0) {
console.log(ret);
return ret;
}
return null;
});
return null;
};
}
I proved this with console.log line, this actually logs my object.
The Validator is attached besides a Validators.required in ngOnInit
ngOnInit() {
...
this.fourthFormGroup = this._formBuilder.group({
dateipfad: ['', {validator: Validators.compose([Validators.required, this.directoryValidator.ValidateDirectory(this.clientID)]), updateOn: 'blur'}]
});
...
}
Problem is: the required Validator works as intended, but my custom Validator just logs.
I have tried quite a lot, like using validators
with array instead of Validators.compose
, tweaked my Validator method to set control.setErrors(ret)
some other things, nothing worked.
I feel like there is quite a simple solution, but I just can't find it...
EDIT 1: I created a stackblitz https://stackblitz.com/edit/angular-ysyb9i?file=src%2Fapp%2Fapp.component.html
Explanation: the input takes any strings, on deselect the validation kicks in.
if Input is 'false' it should set input to invalid by returning const ret: ValidationErrors = { isValidDirectory: true };
, any other string should be valid and it returns null
.
Both results are logged on console, so you can check it. If input is invalid it should show a notification div below (not quite sure, just added it for this stackblitz to show)