-1

I'm new to Angular and find it quite tricky with this validation concept. But I have been looking around the internet and I can't seem to find the answer for my problem. Although there is a lot of good tips and guides about validation for Angular.

So my problem is that I have an dropdown menu with 6 options which user can select. After a user has selected one option I want an input field to change validation. For an example:

If the user select option 1 in the drop down. I want the input field to have the validation required and maximum length 5 tokens.

If the user select option 2 in the drop down. I want the input field to have the validation required and maximum length of 10 tokens.

If the user chose option 6 in the drop down. I want the input field to be disabled with no validation. (If the use chose this option then the validation formgroup should be valid)

Any ideas would be greatly appreciated.

The answer in Angular dropdown validation does not cover changing validation on the input element.

2
  • Does this answer your question? Angular dropdown validation Commented Dec 18, 2019 at 10:34
  • @MEDZ not quite. It was missing subscription on the dropdown meny. So I could change validation. Commented Dec 18, 2019 at 12:53

1 Answer 1

1

You can do this using valueChanges, setValidators() and clearValidators().

First you need to subscribe to each value change of the dropdown menu using valueChanges of the form control. The subscription will emit the new value of the dropdown and with the new value you need to run your logic to decide the validation you need to apply. After that you can use the setValidators() method to set validation for the form control of the input field. If you need to remove the validation you can use the clearValidators() method. You can enable or disable a field using disable() and enable() methods on the form control.

Example:

field1.valueChanges.subscribe((val) => {
  if (val === 'a') {
    field2.setValidators([Validators.minLength(1)]);
  } else {
    field2.clearValidators();
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! yes, subscribing to the dropdown meny fixed it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.