1

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.

2
  • Have you tried (field) => {notValid: true}? Seems it looks like one line. You can also use setErrors Commented Jun 13, 2017 at 16:39
  • Well.. in my opinion, according to the case you described, you don't need setValidators, but setErros method... <control>.setErrors({notValid: true}). Commented Jun 13, 2017 at 17:33

1 Answer 1

2

Firstly, a lambda can turn that into a one-liner, with the caveat that its return value cannot start with a { or else it'll be seen as a function body, so prepend a type-cast like <any>

this.myForm.get('field').setValidators(f => <any>{notValid:true})

Secondly, if the custom validation is conditional on state outside of the form, you may consider moving that boolean check into the validator itself.

.setValidators(f => outsideBoolean ? {notValid:true} : null)

But you still must run updateValueAndValidity() yourself when outsideBoolean changes. Not even as a cross-field validator will the form update itself automatically.

Alternately, don't use angular/forms at all for that boolean.

A 3rd way: use a <input type="hidden" and put the outsideBoolean into that, so it does participate in the form validation machinery.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.