Skip to content

Commit

Permalink
Refactor: simplified code by leveraging \b in IPv4 regular expression
Browse files Browse the repository at this point in the history
Refactor: removed unnecessary !!

Closes validatorjs#1962
  • Loading branch information
UnKnoWn-Consortium committed May 16, 2022
1 parent cfcf911 commit ccd2c69
Showing 1 changed file with 3 additions and 7 deletions.
10 changes: 3 additions & 7 deletions src/lib/isIP.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import assertString from './util/assertString';
* * */
const IPv4SegmentFormat = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
const IPv4AddressFormat = `(${IPv4SegmentFormat}[.]){3}${IPv4SegmentFormat}`;
const IPv4AddressRegExp = new RegExp(`^${IPv4AddressFormat}$`);
const IPv4AddressRegExp = new RegExp(`^\b${IPv4AddressFormat}\b$`);

const IPv6SegmentFormat = '(?:[0-9a-fA-F]{1,4})';
const IPv6AddressRegExp = new RegExp('^(' +
Expand All @@ -51,14 +51,10 @@ export default function isIP(str, version = '') {
return isIP(str, 4) || isIP(str, 6);
}
if (version === '4') {
if (!IPv4AddressRegExp.test(str)) {
return false;
}
const parts = str.split('.').sort((a, b) => a - b);
return parts[3] <= 255;
return IPv4AddressRegExp.test(str);
}
if (version === '6') {
return !!IPv6AddressRegExp.test(str);
return IPv6AddressRegExp.test(str);
}
return false;
}

0 comments on commit ccd2c69

Please sign in to comment.