This is a small question, but it's has bothering me.
I have a scene where I get a value (let's say a boolean) from outside the form, meaning it is not part of formgroup. And based on that value I want to set a custom validator, as it does not apply with the available ones (required,pattern...) Here is a very simplified code to showcase:
So the problem is easy to set a required validator like so:
if(bool) {
this.myForm.get('field').setValidators([Validators.required])
this.myForm.get('field').updateValueAndValidity();
} else ....
I would like a way to set a custom validation error instead. So something like:
this.myForm.get('field').setValidators([{notValid: true}])
But the above don't work, but I need to do that instead:
this.myForm.get('field').setValidators([this.customValidator])
customValidator(field) {
return {notValid: true}
}
Is it not possible to set a custom validation on one line, instead of needing to having customValidator? (or any other better way)
I know, small problem, but it's has been bothering me and code is also actually more complex than here.
PS. I know I could do it and use for example one of the available Validators to mark it as invalid, but I would like clean solution if is possible.
(field) => {notValid: true}? Seems it looks like one line. You can also usesetErrorssetValidators, butsetErrosmethod...<control>.setErrors({notValid: true}).