From 872dd7a8a94225d272718b622106b6ee44738427 Mon Sep 17 00:00:00 2001 From: omer Date: Sat, 30 Nov 2019 22:14:27 +0200 Subject: [PATCH] - supporing underscore in domain name. - URL is valid only if has at least 1 digit/alpha - added loop optimizations --- lib/clean-host.js | 4 +++- lib/is-valid.js | 17 +++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/clean-host.js b/lib/clean-host.js index 4a20697..ddaa9a9 100644 --- a/lib/clean-host.js +++ b/lib/clean-host.js @@ -54,7 +54,9 @@ function checkTrimmingNeeded(value) { * @param {string} value */ function checkLowerCaseNeeded(value) { - for (var i = 0; i < value.length; i += 1) { + let i = 0; + const m = value.length; + for (; i < m; i++) { var code = value.charCodeAt(i); if (code >= 65 && code <= 90) { // [A-Z] return true; diff --git a/lib/is-valid.js b/lib/is-valid.js index 811c9bb..19fcd9e 100644 --- a/lib/is-valid.js +++ b/lib/is-valid.js @@ -62,8 +62,13 @@ module.exports = function isValid(hostname) { var code; var len = hostname.length; - for (var i = 0; i < len; i += 1) { + let i = 0; + let hasAlphaOrDigit = false; + for (; i < len; i++) { code = hostname.charCodeAt(i); + const isAlphaOrDigit = isAlpha(code) || isDigit(code); + hasAlphaOrDigit |= isAlphaOrDigit; + if (code === 46) { // '.' if ( @@ -72,14 +77,16 @@ module.exports = function isValid(hostname) { // Check that previous character was not already a '.' lastCharCode === 46 || // Check that the previous label does not end with a '-' - lastCharCode === 45 + lastCharCode === 45 || + // check that prvious label does not end with a '_' + lastCharCode === 95 ) { return false; } lastDotIndex = i; - } else if (!(isAlpha(code) || isDigit(code) || code === 45)) { - // Check if there is a forbidden character in the label: [^a-zA-Z0-9-] + } else if (!isAlphaOrDigit && !code === 45 && !code === 95) { + // Check if there is a forbidden character in the label: [^a-zA-Z0-9-_] return false; } @@ -87,6 +94,8 @@ module.exports = function isValid(hostname) { } return ( + // has atleast 1 digit or alpha character + hasAlphaOrDigit && // Check that last label is shorter than 63 chars (len - lastDotIndex - 1) <= 63 && // Check that the last character is an allowed trailing label character.