Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module.directive('colorValidate', function() {
- return {
- restrict: 'A',
- scope: {
- color: '=ngModel'
- },
- link: function(scope, element) {
- var previousValue = '#ffffff';
- //pattern that accept #ff0000 or #f00
- var colorPattern = new RegExp('^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$');
- element.on('focus', function() {
- previousValue = scope.color;
- });
- element.on('blur', function() {
- if (!colorPattern.test(scope.color)) {
- scope.$apply(function() {
- scope.color = previousValue;
- });
- }
- else {
- scope.$apply(function() {
- scope.color = scope.color.toLowerCase();
- });
- }
- });
- }
- };
- });
- <input color-validate type="text" ng-model="color.color"/>
- describe('colorValidate directive', function() {
- var scope,
- elem,
- compiled,
- html;
- beforeEach(function() {
- html = '<input color-validate type="text" ng-model="color.color"/>';
- inject(function($compile, $rootScope) {
- scope = $rootScope.$new();
- scope.color = {color: '#aaaaaa'};
- elem = angular.element(html);
- compiled = $compile(elem);
- compiled(scope);
- scope.$digest();
- });
- });
- it('should permit valid 6-chars color value', function() {
- elem.focus();
- elem.val('#FF0000');
- elem.blur();
- scope.$digest();
- expect(elem.val()).toBe('#FF0000');
- });
- it('should reject non valid color values', function() {
- elem.focus();
- elem.val('#F00F');
- scope.$digest();
- elem.blur();
- expect(elem.val()).toBe('#aaaaaa');
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement