Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-class validation is not working in AngularJS

I tried to put green background if it is edited and valid.

But, even for invalid also it is showing green background. On invalid it should show the yellow background with red text.

Thanks in advance for giving me the solution.

html

<div ng-app="myApp" ng-controller="formCtrl">

    <form name="inputform">
        <div ng-class="{'has-success': inputform.email.$dirty && inputform.email.$valid, 'has-error': inputform.email.$dirty && inputform.email.$invalid}">
            <label for="exampleInputEmail1">Email</label>
            <input type="text" name="email" ng-model="data.email" id="exampleInputEmail1" />
        </div>
    </form>

    {{data}}

</div>

javascript

var module = angular.module("myApp", []);

module.controller("formCtrl", ['$scope', function($scope){

    $scope.data = {};

}]);

css

.has-error {
    color: red;
    background-color: red;
}

.has-success {
    color: black;
    background-color: green;
}
like image 382
Manoj Avatar asked Jul 28 '26 11:07

Manoj


1 Answers

There is no validation applied to that input element so it is valid all the time. Try the below form, I've applied the required and email validation:

(It will only be green if a proper email address in entered)

var module = angular.module("myApp", []);

module.controller("formCtrl", ['$scope', function($scope){

    $scope.data = {};

}]);
.has-error {
    color: red;
    background-color: red;
}

.has-success {
    color: black;
    background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="formCtrl">

    <form name="inputform">
        <div ng-class="{'has-success': inputform.email.$valid, 'has-error': inputform.email.$invalid}">
            <label for="exampleInputEmail1">Email</label>
            <input type="email" name="email" required ng-model="data.email" id="exampleInputEmail1" />
        </div>
    </form>

    {{data}}

</div>

Alternatively, you can use this library to provide Bootstrap form validation in simple way.

like image 75
Shashank Agrawal Avatar answered Jul 30 '26 00:07

Shashank Agrawal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!