Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS and Bootstrap: Red border on invalid input field on submit

I've this basic form implemented using AngularJS and Bootstrap: http://jsfiddle.net/dennismadsen/0stwd03k/

HTML

<div ng-controller="MyCtrl">
    <form class="well" name="formTest" ng-submit="save()">
        <div class="form-group">
            <label for="name">Name*</label>
            <input type="name" class="form-control" id="name" placeholder="Enter name" required />
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
    </form>
</div>

JavaScript

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

function MyCtrl($scope) {

    $scope.save = function () {
    };
}

Result

enter image description here

The Name input field is required. When I click the submit button, I need the input field to have a red border if it's invalid. How can this be done?

Alternatively, if I unfocus the input field and it's still not valid, it would be great that the red corder is shown on that time, instead of waiting for the form submit.

like image 579
dhrm Avatar asked Mar 19 '15 12:03

dhrm


2 Answers

Twitter Bootstrap has an has-error class, so I would use this in conjunction with ng-class for the form group, then a label with the label and label-danger classes for good measure:

<div class="form-group" ng-class="{'has-error': errors.Name }">
    <label for="name">Name*</label>
    <input type="name" class="form-control" id="name" placeholder="Enter name" required />
    <span class="label label-danger" ng-if="errors.Name">{{errors.Name}}</span>
</div>

Then in your controller, have an errors object, and set the Name property of this to a string when the name is invalid.

like image 183
JMK Avatar answered Sep 23 '22 17:09

JMK


The first thing you were missing was adding ng-model='name' to input field, then only will the form become invalid once you click submit, otherwise the form will always be valid since it considers that there is no field present.

Then I'd add the submitted class on the submit click button, then put the border css like .submitted would be the parent and .ng-invalid would be the child so we can put the style on .submitted .ng-invalid

HTML

<div ng-controller="MyCtrl">
    <form class="well" name="formTest" ng-class="{'submitted': submitted}" ng-submit="save()" >
        <div class="form-group">
            <label for="name">Name*</label>
            <input type="name" class="form-control" id="name" placeholder="Enter name" ng-model="name" required />
        </div>{{submitted}}
        <button type="submit" class="btn btn-default" ng-click="submitted= true;">Submit</button>
    </form>
</div>

CSS

.submitted .ng-invalid{
    border: 1px solid red;
}

Working Fiddle

Hope this could help you, Thanks.

like image 20
Pankaj Parkar Avatar answered Sep 22 '22 17:09

Pankaj Parkar