isInt.js 825 B

123456789101112131415161718
  1. import assertString from './util/assertString';
  2. var _int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/;
  3. var intLeadingZeroes = /^[-+]?[0-9]+$/;
  4. export default function isInt(str, options) {
  5. assertString(str);
  6. options = options || {};
  7. // Get the regex to use for testing, based on whether
  8. // leading zeroes are allowed or not.
  9. var regex = options.allow_leading_zeroes === false ? _int : intLeadingZeroes;
  10. // Check min/max/lt/gt
  11. var minCheckPassed = !options.hasOwnProperty('min') || str >= options.min;
  12. var maxCheckPassed = !options.hasOwnProperty('max') || str <= options.max;
  13. var ltCheckPassed = !options.hasOwnProperty('lt') || str < options.lt;
  14. var gtCheckPassed = !options.hasOwnProperty('gt') || str > options.gt;
  15. return regex.test(str) && minCheckPassed && maxCheckPassed && ltCheckPassed && gtCheckPassed;
  16. }