Home Ask Login Register

Developers Planet

Your answer is one click away!

Matt Schley February 2016

Using ng-class with mutiple conditions

I want to set 1 of 3 different classes on a span based on the result of a function. My javascript below seems to be returning the correct value, however my markup is always showing the 'require-matched' class. How can I write an ng-class directive to accommodate this?


<span ng-class="{'require-empty': 0,
                                 'require-matched': 1,
                                 'require-not-matched':2 [form.username.$validators.status]}">


ctrl.$validators.status = function (value) {
                var expression = /^[-\w]+$/;

                if (value != null && value != undefined && value != '' && value != ' ') {
                    if (expression.test(value))
                        return 1;
                    if (!expression.test(value))
                        return 2;
                else {
                    return 0;


dfsq February 2016

This is incorrect usage of validation in Angular. ctrl.$validators.status should return boolean: true for valid result (required-matched in your terminology) and false otherwise (required-not-match). In case of invalid validation ngModelController will receive boolean flag which you can use in view to style control or show error message.

require-empty that you have should be handled by required validator instead of making status validator do this also.

So what you would probably want to have:

ctrl.$validators.status = function(value) {
    if (value) {
        var expression = /^[-\w]+$/;
        return expression.test(value.trim());
    return false;

or directive can be as concise as

ctrl.$validators.status = function(value) {
    return value && /^[-\w]+$/.test(value.trim());

Corresponding field in HTML will be (providing that the directive name is status):

<input type="text" name="test" ng-model="testModel" status required>

<div class="error" ng-show="testForm.test.$error.required">The field is required.</div>
<div class="error" ng-show="testForm.test.$error.status">The value should match pattern.</div>

Demo: http://plnkr.co/edit/YALB4Vbi5FzNH5FCfwB5?p=preview

Post Status

Asked in February 2016
Viewed 2,828 times
Voted 13
Answered 1 times


Leave an answer

Quote of the day: live life