Kenn
Kenn

Reputation: 2769

how to make an angular input not be required when it's not shown

I have the following code

<div class="form-group" show-errors ng-show="contact.ContactType === 'LegallyMarriedSpouse' || contact.ContactType === 'Self'">
   <label class="control-label">Social Security Number</label>
   <input type="text" class="form-control" ng-model="contact.SSN" ui-mask="999-99-9999" name="SSN" maxlength="50" required />
</div>

I would have thought that Angular would have made sure that the hidden field was no longer required however that is not the case. although the user can't see it it's clearly still stopping the form from being submitted because I see the following error in the console.

An invalid form control with name='SSN' is not focusable.

So - the question is how do I handle this? If it's displayed I want it to be required if not obviously we can't try and force the user to fill out the values.

Upvotes: 0

Views: 46

Answers (1)

JB Nizet
JB Nizet

Reputation: 692121

2 solutions:

  • use ng-if rather than ng-show to remove the input from the form rather than hiding it
  • instead of required, use ng-required="contact.ContactType === 'LegallyMarriedSpouse' || contact.ContactType === 'Self'" to make it required only when the condition showing the field is true. You should put that complex condition in a scope function though, to avoid duplicating it.

Note however that even if the form is invalid, it can still be submitted, unless you're explicitely preventing it by disabling its submit button when the form is invalid. I don't think the error you're seeing has anything to do with the form being invalid.

Also note that the second solution will only deal with the field being required. If the value inside the field is too long or doesn't match with the mask, the field will stay invalid. So you should probably use the first solution.

Upvotes: 1

Related Questions