Skip to content

Instantly share code, notes, and snippets.

@neilbo
Created September 22, 2014 14:16
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 neilbo/57ab827c241c412046bf to your computer and use it in GitHub Desktop.
Save neilbo/57ab827c241c412046bf to your computer and use it in GitHub Desktop.
Show error on blur, and use myFormSubmitted
.form-group .help-block {
display: none;
}
.form-group.has-error .help-block {
display: block;
}
<div>
<form name="myForm" novalidate>
<div class="form-group" ng-class="{true: 'has-error'}[myFormSubmitted && myForm.firstName.$invalid]" show-errors>
<label class="control-label">First Name</label>
<input type="text" class="form-control" name="firstName" maxlength="256" ng-maxlength="256" required/>
<p class="help-block" ng-show="myForm.firstName.$error.required">Enter your first name</p>
<p class="help-block" ng-show="myForm.firstName.$error.maxlength">Your first name is too long</p>
</div>
<div>
<button class="btn btn-primary" ng-click="myFormSubmitted=true">Continue</button>
</div>
</form>
</div>
// http://blog.yodersolutions.com/bootstrap-form-validation-done-right-in-angularjs/
//show errors on blur
angular.module('myApp')
.directive('showErrors', function() {
return {
restrict: 'A',
require: '^form',
link: function(scope, el, attrs, formCtrl) {
// find the text box element, which has the 'name' attribute
var inputEl = el[0].querySelector('[name]');
// convert the native text box element to an angular element
var inputNgEl = angular.element(inputEl);
// get the name on the text box
var inputName = inputNgEl.attr('name');
// only apply the has-error class after the user leaves the text box
var blurred = false;
inputNgEl.bind('blur', function() {
blurred = true;
el.toggleClass('has-error', formCtrl[inputName].$invalid);
});
scope.$watch(function() {
return formCtrl[inputName].$invalid;
}, function(invalid) {
// we only want to toggle the has-error class after the blur
// event or if the control becomes valid
if (!blurred && invalid) {
return;
}
el.toggleClass('has-error', invalid);
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment