Skip to content

Instantly share code, notes, and snippets.

@cpitt
Last active August 29, 2015 14:02
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 cpitt/fb2223f3ca1470257a9c to your computer and use it in GitHub Desktop.
Save cpitt/fb2223f3ca1470257a9c to your computer and use it in GitHub Desktop.
angular bootstrap validation
angular.module('bootstrap.validation', [])
/*
If you want errors to show up after submit is hit then your submit action needs to
set your form's controller's .submitted value to true
*/
/* example of a custom validation */
.directive('dateValidation', function(){
return{
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ngModel ){
function validate(value) {
ngModel.$setValidity('date', /[\d]{2}-.*-[\d]{4}/.test(value))
}
scope.$watch( function(){
return ngModel.$viewValue
}, validate)
}
}
})
/* Error Messages for default error types
/ TODO: complete list and add a way to append custom error types as well as override defaults*/
.constant('errorMessages', {
'required': 'is required',
'date': 'is invalid',
'minlength': 'is too short',
'maxlength': 'is too long'
})
.directive("bootstrapError", [ '$parse', 'errorMessages' ,function($parse, errorMessages){
return {
restrict: 'EA',
template: "<div class='help-block' ng-repeat='(errorKey, errorValue) in errors' ng-hide='bootstrapValid'>"+
"<small ng-show='errorValue'>{{ errorMessages[errorKey] }}</small>"+
"</div>",
replace: true,
require: '^form',
scope: {},
link: function(scope, element, attrs, formCtrl){
var formGroup = element.parent()
var inputElement = formGroup[0].querySelector('input[name], select[name], textarea[name]')
var inputCtrl = formCtrl[inputElement.name]
var bootstrapValid = function() {
return inputCtrl.$valid || (inputCtrl.$pristine && !formCtrl.submitted)
}
scope.errors = inputCtrl.$error
scope.errorMessages = errorMessages
scope.$watch(bootstrapValid, function(){
scope.bootstrapValid = bootstrapValid()
})
}
}
}])
.directive("bootstrapValidate", function(){
return {
restrict: 'A',
require: '^form',
link: function(scope, element, attrs, formCtrl){
var inputElement = element[0].querySelector('input[name], select[name], textarea[name]')
var inputCtrl = formCtrl[inputElement.name]
var bootstrapValid = function() {
return inputCtrl.$valid || (inputCtrl.$pristine && !formCtrl.submitted)
}
scope.$watch(bootstrapValid, function(){
if (!bootstrapValid()){
element.addClass('has-error')
} else {
element.removeClass('has-error')
}
})
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment