Skip to content

Instantly share code, notes, and snippets.

@johannes-weber
Last active January 24, 2016 10:35
Show Gist options
  • Save johannes-weber/8975897 to your computer and use it in GitHub Desktop.
Save johannes-weber/8975897 to your computer and use it in GitHub Desktop.
AngularJS Custom Float Validation
'use strict';
/**
* This directive parses both 1.2 and 1,2 into a valid float number 1.2.
* Note that you can't use input type number here as HTML5 browsers would
* not allow the user to type what it would consider an invalid number such as 1,2.
*
* <input ng-model="{yourModel}" validate-float />
*/
angular.module('Library').directive('validateFloat', function () {
var FLOAT_REGEXP = /^\-?\d+((\.|\,)\d+)?$/;
return {
require: "ngModel",
link: function(scope, elm, attrs, ngModelController){
ngModelController.$parsers.unshift(function(viewValue) {
if (viewValue == '') {
ngModelController.$setValidity('float', true);
return viewValue;
}
if (FLOAT_REGEXP.test(viewValue)) {
ngModelController.$setValidity('float', true);
return parseFloat(viewValue.replace(',', '.'));
}
ngModelController.$setValidity('float', false);
return undefined;
});
}
};
});
'use strict';
describe('Validate Float Directive Test', function () {
var rootScope,
scope,
inputElement,
$body = angular.element('body'),
simpleHtml = '<input ng-model="modelValue" validate-float>';
beforeEach(function () {
module('Library');
inject(function($injector, $compile) {
rootScope = $injector.get('$rootScope');
inputElement = $compile(angular.element(simpleHtml))(rootScope);
});
});
afterEach(function () {
$body.empty();
});
it('Should add a invalid class for a non-float value', function () {
inputElement.val('XYZ');
inputElement.trigger('input');
rootScope.$digest();
// check assigned state classes
expect(inputElement.hasClass('ng-valid')).toBeFalsy();
expect(inputElement.hasClass('ng-invalid-float')).toBeTruthy();
// check scopes model value
expect(rootScope.modelValue).toBeUndefined();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment