Skip to content
This repository has been archived by the owner on Nov 24, 2018. It is now read-only.

Commit

Permalink
fix(digitsValidator): Use combination of Number constructor and toStr…
Browse files Browse the repository at this point in the history
…ing() to split number to integer and fraction parts

- fixes a bug when the current locale uses ',' as decimal separator
  • Loading branch information
Philipp Denzler committed Dec 2, 2014
1 parent cd1088d commit 81245b0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/core/validators/digitsValidator.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ angular.module('valdr')

.factory('valdrDigitsValidator', ['valdrUtil', function (valdrUtil) {

var decimalSeparator = 1.1.toLocaleString().substring(1, 2); // jshint ignore:line

var removeAnythingButDigitsAndDecimalSeparator = function (value) {
var regex = new RegExp('[^' + decimalSeparator + '\\d]', 'g');
// at this point 'value' can still be a number or a string or...
return value.toLocaleString().replace(regex, '');
// matches everything except digits and '.' as decimal separator
var regexp = new RegExp('[^.\\d]', 'g');

/**
* By converting to number and back to string using toString(), we make sure that '.' is used as decimal separator
* and not the locale specific decimal separator.
* As we already checked for NaN at this point, we can do this safely.
*/
var toStringWithoutThousandSeparators = function (value) {
return Number(value).toString().replace(regexp, '');
};

var isNotLongerThan = function (valueAsString, maxLengthConstraint) {
Expand All @@ -19,8 +23,8 @@ angular.module('valdr')
fractionConstraint = constraint.fraction,
cleanValueAsString, integerAndFraction;

cleanValueAsString = removeAnythingButDigitsAndDecimalSeparator(value);
integerAndFraction = cleanValueAsString.split(decimalSeparator);
cleanValueAsString = toStringWithoutThousandSeparators(value);
integerAndFraction = cleanValueAsString.split('.');

return isNotLongerThan(integerAndFraction[0], integerConstraint) &&
isNotLongerThan(integerAndFraction[1], fractionConstraint);
Expand Down
6 changes: 6 additions & 0 deletions src/core/validators/digitsValidator.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ describe('valdrDigitsValidator', function () {
expect(digitsValidator.validate('47\'11', constraint)).toBe(false);
});

it('should validate correctly with fraction > 4', function() {
constraint.fraction = 4;
expect(digitsValidator.validate(1000.00001, constraint)).toBe(false);
expect(digitsValidator.validate(1000.0001, constraint)).toBe(true)
});

it('should not choke on integer:1 conditions', function () {
constraint.integer = 1;
expect(digitsValidator.validate('10', constraint)).toBe(false);
Expand Down

0 comments on commit 81245b0

Please sign in to comment.