From a3e3880203ec17f65488dfdc500db3d85d5d0975 Mon Sep 17 00:00:00 2001 From: Sarah Ryan Date: Fri, 27 May 2016 13:53:11 -0700 Subject: [PATCH] Add `allow_leading_zeroes` option to isInt() --- src/lib/isInt.js | 19 ++++++++++++++++--- test/validators.js | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/lib/isInt.js b/src/lib/isInt.js index d49f55ea2..01fbd1c97 100644 --- a/src/lib/isInt.js +++ b/src/lib/isInt.js @@ -1,10 +1,23 @@ import assertString from './util/assertString'; -const int = /^[-+]?[0-9]+$/; +const int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/; +const intLeadingZeroes = /^[-+]?[0-9]+$/; export default function isInt(str, options) { assertString(str); options = options || {}; - return int.test(str) && (!options.hasOwnProperty('min') || - str >= options.min) && (!options.hasOwnProperty('max') || str <= options.max); + + // Get the regex to use for testing, based on whether + // leading zeroes are allowed or not. + let regex = ( + options.hasOwnProperty('allow_leading_zeroes') && options.allow_leading_zeroes ? + intLeadingZeroes : + int + ); + + // Check min/max + let minCheckPassed = (!options.hasOwnProperty('min') || str >= options.min); + let maxCheckPassed = (!options.hasOwnProperty('max') || str <= options.max); + + return regex.test(str) && minCheckPassed && maxCheckPassed; } diff --git a/test/validators.js b/test/validators.js index 2a68015e3..7ea387772 100644 --- a/test/validators.js +++ b/test/validators.js @@ -883,6 +883,27 @@ describe('Validators', function () { it('should validate integers', function () { test({ validator: 'isInt', + valid: [ + '13', + '123', + '0', + '123', + '-0', + '+1', + ], + invalid: [ + '01', + '-01', + '000', + '100e10', + '123.123', + ' ', + '', + ], + }); + test({ + validator: 'isInt', + args: [{ allow_leading_zeroes: true }], valid: [ '13', '123', @@ -893,6 +914,8 @@ describe('Validators', function () { '01', '-01', '000', + '-000', + '+000', ], invalid: [ '100e10',