Awakening Awakening - 6 months ago 13
AngularJS Question

Angular form validation: how to override $invalid

enter image description here

<div class="col-xs-7">
<div class="checkbox">
<label>
<input type="checkbox" ng-model="settings.input">
checked
</label>
</div>
<div collapse="!settings.input" ng-class="myform.input.$invalid ? 'has-error has-feedback': ''">
<input type="number" class="form-control input-sm" id="inputEmail3" name="input" ng-model="settings.input" placeholder="if checked, then do validation" required min="0">
<span ng-show="myform.input.$invalid" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>
</div>
</div>


demo here

My question is when I set
required
for the
input
, the
form.$valid
will be false, But what I want is only when the
checkbox
checked, then do
input
validation, So when not checked, even the
input
is empty, the value of
form.$valid
should be true

What I purpose is to override the
$valid
of
input
, how to override?

Answer

Angular has ng-required directive that allows to enable required attribute with an expression. Replace required="" on input with the following:

ng-required="settings.checked"

Live example