Skip to content

Commit

Permalink
Add allow_leading_zeroes option to isInt()
Browse files Browse the repository at this point in the history
  • Loading branch information
theartoflogic committed May 27, 2016
1 parent f624d46 commit a3e3880
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
19 changes: 16 additions & 3 deletions src/lib/isInt.js
Original file line number Diff line number Diff line change
@@ -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;
}
23 changes: 23 additions & 0 deletions test/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -893,6 +914,8 @@ describe('Validators', function () {
'01',
'-01',
'000',
'-000',
'+000',
],
invalid: [
'100e10',
Expand Down

0 comments on commit a3e3880

Please sign in to comment.