Search code examples
javascripthtmlangularvalidation

How to enable validations only when the HTML element is active using Angular 2?


I have a radio button and a corresponding input text box which is displayed when radio button is checked. I have kept the validation attribute required on the input tag as shown:

<input type="text" id="textbox" required />

This textbox hides when I deselect the radio button. However, I could not submit the form even if the text box is hidden. After all, a required field that is hidden is still required, and so I can't just put the required attribute on those hidden field.

Having explained my scenario:

Is there any "HTML-Only" approach to allow validations only when the textbox is active? If not, how can I achieve the same using Angular 2 (or vanilla JavaScript)?


Solution

  • You can use ' ng-if ' instead of 'ng-show / ng-hide ' while showing/hiding input box. Because , ng-show/hide only hides the element , but it is there in DOM , while ng-if generates element only when condition is fullfilled