validatorjs / validator.js

String validation
MIT License
23.01k stars 2.29k forks source link

Ports starting with multiple zeros pass the verification #2208

Closed hancao97 closed 5 months ago

hancao97 commented 1 year ago

Describe the bug When I add 0 in front of a port string, just like ‘00065535’,I expect false,but the function return true.

Examples

validator.isPort('0001');
validator.isURL('https://www.google.com:0001');
// return true, but expect false

Source Code: I can't configure the options of isInt when I use isPort api

// isPort
import isInt from './isInt';

export default function isPort(str) {
  return isInt(str, { min: 0, max: 65535 });
}
// isInt
import assertString from './util/assertString';

const int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/;
const intLeadingZeroes = /^[-+]?[0-9]+$/;

export default function isInt(str, options) {
  assertString(str);
  options = options || {};

  // 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 ?
      int : intLeadingZeroes
  );

  // Check min/max/lt/gt
  let minCheckPassed = (!options.hasOwnProperty('min') || str >= options.min);
  let maxCheckPassed = (!options.hasOwnProperty('max') || str <= options.max);
  let ltCheckPassed = (!options.hasOwnProperty('lt') || str < options.lt);
  let gtCheckPassed = (!options.hasOwnProperty('gt') || str > options.gt);

  return regex.test(str) && minCheckPassed && maxCheckPassed && ltCheckPassed && gtCheckPassed;
}

Additional context Validator.js version: 13.7.7 Node.js version: v16.12.0 OS platform: macOS

niuzhihao commented 1 year ago

I has the same problem! 😢

anasshakil commented 1 year ago

Try this

allow_leading_zeroes: false

// isPort
import isInt from './isInt';

export default function isPort(str) {
  return isInt(str, { allow_leading_zeroes: false, min: 0, max: 65535 });
}
hancao97 commented 1 year ago

This is the internal implementation of validatorjs, so I can't pass in options:

https://github.com/validatorjs/validator.js/blob/master/src/lib/isPort.js

At the same time, we need to think about how to configure the port format in 'isUrl'

hancao97 commented 1 year ago

This is the internal implementation of validatorjs, so I can't pass in options:

https://github.com/validatorjs/validator.js/blob/master/src/lib/isPort.js

At the same time, we need to think about how to configure the port format in 'isUrl'

anasshakil commented 1 year ago

This is the internal implementation of validatorjs, so I can't pass in options:

https://github.com/validatorjs/validator.js/blob/master/src/lib/isPort.js

I will create PR but seems like maintainers are not actively merging PRs, that's why I’ve suggested you edit your local version.