Skip to content

Instantly share code, notes, and snippets.

@intellix
Created February 13, 2014 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intellix/8972017 to your computer and use it in GitHub Desktop.
Save intellix/8972017 to your computer and use it in GitHub Desktop.
One field with validation Bootstrap/Angular
<div class="form-group" ng-class="{'has-error': stepForm.email.$invalid && (stepForm.email.$dirty || stepForm.submitted), 'has-success': !stepForm.email.$invalid, 'has-feedback': (stepForm.email.$invalid && stepForm.email.$dirty) || !stepForm.email.$invalid || stepForm.submitted}">
<div class="col-md-12">
<input type="email" placeholder="{{ 'Email' | translate }}" class="form-control" ng-model="user.email" name="email" required>
<span class="glyphicon form-control-feedback" ng-class="{'glyphicon-ok': !stepForm.email.$invalid, 'glyphicon-remove': stepForm.email.$invalid && (stepForm.email.$dirty || stepForm.submitted)}" ng-show="(stepForm.email.$invalid && stepForm.email.$dirty) || !stepForm.email.$invalid || stepForm.submitted"></span>
<p class="help-block error" ng-show="stepForm.email.$error.required && (stepForm.email.$dirty || stepForm.submitted)">{{ 'This field is required' | translate }}</p>
<p class="help-block error" ng-show="stepForm.email.$error.email && (stepForm.email.$dirty || stepForm.submitted)">{{ 'Email is in the wrong format' | translate }}</p>
</div>
</div>
@johnschult
Copy link

I have looked at this a couple times now... I sure wish I had a directive that did this 😃

@StephenRedd
Copy link

Here is a directive that does "kinda" this same thing. In my case though, I didn't care about the submitted value, and I don't want to show the OK icon, just the remove icon. It can be adapted to fit whatever validation behavior you want though.

(function () {
'use strict';

angular
    .module('app')
    .directive('dirtyFeedback', [dirtyFeedback]);

function dirtyFeedback() {

    var directive = {
        link: link,
        restrict: 'A',
        require: '^form'
    };
    return directive;

    function link(scope, element, attrs, frmCtrl) {
        var pEl = element.parent()[0].querySelector('[name]');
        var pNgEl = angular.element(pEl);
        var pName = pNgEl.attr('name');
        var ctrl = frmCtrl[pName];

        scope.$watch(function () {
            return ctrl.$invalid && ctrl.$dirty;
        }, function (newValue) {
            element.toggleClass('glyphicon-remove', newValue);
        });
    }
}


})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment