Halama
Halama

Reputation: 275

How to assign class if input is invalid?

I have the following HTML element:

<input type="text" ng-model="form.artist" ng-class="form.artist.$invalid ? 'error' : ''" required ng-minlength="4">

But it does not work when I have invalid input "form.artist"

Upvotes: 1

Views: 6380

Answers (4)

devqon
devqon

Reputation: 13997

You have to put a name attribute to your input, then your $invalid flag comes of [formName].[inputName].$invalid:

<form name="myForm">
    <input type="text" name="artist" required
           ng-minlength="4"
           ng-model="form.artist" 
           ng-class="myForm.artist.$invalid ? 'error' : ''" />
    <!-- or ng-class="{error:myForm.artist.$invalid}" -->
</form>

See this jsfiddle

See also the documentation of angular:

Similarly, an input control that has the ngModel directive holds an instance of NgModelController. Such a control instance can be published as a property of the form instance using the name attribute on the input control. The name attribute specifies the name of the property on the form instance.

Upvotes: 0

user3414092
user3414092

Reputation: 77

<form name="demoForm">

<input type="text" name="demoForm.artist" ng-model="form.artist" ng-class="{'yourclassname': demoForm.artist.$invalid && demoForm.artist.$dirty}">

</form>

Upvotes: 3

VadimB
VadimB

Reputation: 5711

Yes, you can use ng-class attribute another way:

<input type="text" ng-model="form.artist" ng-class="{'error': form.artist.$invalid}">

Upvotes: 0

Mahesh Shukla
Mahesh Shukla

Reputation: 186

Use this

<div ng-class="{'class-name': 'condition'(boolean)}" </div>

In your case <input type="text" ng-model="form.artist" ng-class="{'class-name':'form.artist.$invalid}">

Upvotes: 0

Related Questions