Created
September 22, 2014 14:16
-
-
Save neilbo/57ab827c241c412046bf to your computer and use it in GitHub Desktop.
Show error on blur, and use myFormSubmitted
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.form-group .help-block { | |
display: none; | |
} | |
.form-group.has-error .help-block { | |
display: block; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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