I have a problem where my CSS is not taking effect (in Chrome), and I think there is some conflict with Twitter Bootstrap.
input.ng-invalid {
border-color: red;
outline-color: red;
}
My pattern is defined in my controller as:
$scope.hexPattern = /^[0-9A-Fa-f]+$/;
And copying the HTML from the live DOM, I see that both ng-invalid
and ng-invalid-pattern
are set, so my ng-pattern
must be working.
<div class="control-group">
<label class="control-label" for="salt">Salt: </label>
<div class="controls">
<input type="text" id="salt" ng-model="salt" ng-pattern="hexPattern" class="ng-dirty ng-invalid ng-invalid-pattern">
</div>
</div>
I see that in the "Validation states" section of the Forms section of Twitter Bootstrap Base CSS, I see I need to add the error
class to the control-group div.
<div class="control-group error">
Question: How to set the class=error
based on the child input class=ng-invalid
? Can this be done with some soft of ng-class expression? Can I set this via code in the controller? Is there a way to ".$watch" the pattern evaluation like property changes? Any other ideas to get my "red" outline?
You can easily do it with ng-class
directive:
<form name="myForm">
<div class="control-group" ng-class="{ error: myForm.salt.$invalid }">
<label class="control-label" for="salt">Salt: </label>
<div class="controls">
<input type="text" name="salt" ng-model="salt" ng-pattern="hexPattern">
</div>
</div>
</form>
http://plnkr.co/edit/RihsxA?p=preview
EDIT
Example with bootstrap 3.3.5 and angular 1.4.2:
<form name="myForm">
<div class="form-group" ng-class="{ 'has-error': myForm.salt.$invalid }">
<label class="control-label" for="salt">Salt: </label>
<input class="form-control" type="text" name="salt" ng-model="salt" ng-pattern="hexPattern">
</div>
</form>
http://plnkr.co/edit/5JNCrY8yQmcnA9ysC7Vc?p=preview
I think a better solution is to just add your own CSS rules. It makes the code much simpler and, as a bonus, you can set the rule to only apply to "dirty" elements. That way fields will only be highlighted after the user has tried to enter something.
In my application I've just added this css, based on an example in the AngularJS forms documentation.
/* Forms */
.ng-invalid.ng-dirty {
border-color: red;
outline-color: red;
}
.ng-valid.ng-dirty {
border-color: green;
outline-color: green;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With