add number validator support for negative numbers, large numbers

This commit is contained in:
Keith Grant 2020-10-20 15:44:17 -07:00
parent a9c01e891f
commit 9b5e59f045
2 changed files with 14 additions and 1 deletions

View File

@ -79,7 +79,11 @@ export function integer(i18n) {
export function number(i18n) {
return value => {
const str = String(value);
if (/^[0-9]*(\.[0-9]*)?$/.test(str)) {
if (/^-?[0-9]*(\.[0-9]*)?$/.test(str)) {
return undefined;
}
// large number scientific notation (e.g. '1e+21')
if (/^-?[0-9]*e[+-][0-9]*$/.test(str)) {
return undefined;
}
return i18n._(t`This field must be a number`);

View File

@ -121,10 +121,19 @@ describe('validators', () => {
expect(number(i18n)('13')).toBeUndefined();
});
test('number should accept negative number', () => {
expect(number(i18n)(-14)).toBeUndefined();
});
test('number should accept decimal/float', () => {
expect(number(i18n)(13.1)).toBeUndefined();
});
test('number should accept large number', () => {
expect(number(i18n)(999999999999999999999.9)).toBeUndefined();
expect(number(i18n)(-999999999999999999999.9)).toBeUndefined();
});
test('number should reject string containing alphanum', () => {
expect(number(i18n)('15a')).toEqual({
id: 'This field must be a number',