Last active
June 1, 2016 10:44
-
-
Save dataslask/708d70c0bdd8270bfa9a4af752af86ff to your computer and use it in GitHub Desktop.
Provides validation messages and styling with AngularJS and Bootstrap.
This file contains 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
/* | |
Provides validation messages and styling with AngularJS and Bootstrap. | |
Example usage: | |
<div class="form-group" my-validate="My validation message"> | |
<label class="control-label" for="copies">Copies:</label> | |
<input id="copies" name="copies" type="number" class="form-control" required min="1" ng-model="copies" /> | |
</div> | |
This is free and unencumbered software released into the public domain. | |
Anyone is free to copy, modify, publish, use, compile, sell, or | |
distribute this software, either in source code form or as a compiled | |
binary, for any purpose, commercial or non-commercial, and by any | |
means. | |
For more information, please refer to <http://unlicense.org/> | |
*/ | |
(function () { | |
"use strict"; | |
angular.module('my-module').directive('myValidate', function () { | |
return { | |
restrict: 'A', | |
require: '^form', | |
link: function(scope, element, attrs, form) { | |
var formGroup = element[0]; | |
var inputElement = formGroup.querySelector('.form-control[name]'); | |
if (!inputElement) { | |
throw "Cannot find required .form-control[name]"; | |
} | |
var ngHelpText = angular.element("<span style='display:none' class='help-block'>" + attrs.myValidate + "</span>"); | |
angular.element(formGroup).append(ngHelpText); | |
scope.$watch(function () { | |
if (form[inputElement.name].$invalid && (form[inputElement.name].$dirty || form.$submitted)) { | |
angular.element(formGroup).addClass('has-error'); | |
ngHelpText.show(); | |
} else { | |
angular.element(formGroup).removeClass('has-error'); | |
ngHelpText.hide(); | |
} | |
}); | |
} | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment