Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add isUrlResolvable validator and tests This commit adds a new… #2205

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ Validator | Description
**isTime(str [, options])** | check if the string is a valid time e.g. [`23:01:59`, new Date().toLocaleTimeString()].<br/><br/> `options` is an object which can contain the keys `hourFormat` or `mode`.<br/><br/>`hourFormat` is a key and defaults to `'hour24'`.<br/><br/>`mode` is a key and defaults to `'default'`. <br/><br/>`hourFomat` can contain the values `'hour12'` or `'hour24'`, `'hour24'` will validate hours in 24 format and `'hour12'` will validate hours in 12 format. <br/><br/>`mode` can contain the values `'default'` or `'withSeconds'`, `'default'` will validate `HH:MM` format, `'withSeconds'` will validate the `HH:MM:SS` format.
**isTaxID(str, locale)** | check if the string is a valid Tax Identification Number. Default locale is `en-US`.<br/><br/>More info about exact TIN support can be found in `src/lib/isTaxID.js`.<br/><br/>Supported locales: `[ 'bg-BG', 'cs-CZ', 'de-AT', 'de-DE', 'dk-DK', 'el-CY', 'el-GR', 'en-CA', 'en-GB', 'en-IE', 'en-US', 'es-ES', 'et-EE', 'fi-FI', 'fr-BE', 'fr-CA', 'fr-FR', 'fr-LU', 'hr-HR', 'hu-HU', 'it-IT', 'lb-LU', 'lt-LT', 'lv-LV', 'mt-MT', 'nl-BE', 'nl-NL', 'pl-PL', 'pt-BR', 'pt-PT', 'ro-RO', 'sk-SK', 'sl-SI', 'sv-SE' ]`.
**isURL(str [, options])** | check if the string is a URL.<br/><br/>`options` is an object which defaults to `{ protocols: ['http','https','ftp'], require_tld: true, require_protocol: false, require_host: true, require_port: false, require_valid_protocol: true, allow_underscores: false, host_whitelist: false, host_blacklist: false, allow_trailing_dot: false, allow_protocol_relative_urls: false, allow_fragments: true, allow_query_components: true, disallow_auth: false, validate_length: true }`.<br/><br/>`require_protocol` - if set to true isURL will return false if protocol is not present in the URL.<br/>`require_valid_protocol` - isURL will check if the URL's protocol is present in the protocols option.<br/>`protocols` - valid protocols can be modified with this option.<br/>`require_host` - if set to false isURL will not check if host is present in the URL.<br/>`require_port` - if set to true isURL will check if port is present in the URL.<br/>`allow_protocol_relative_urls` - if set to true protocol relative URLs will be allowed.<br/>`allow_fragments` - if set to false isURL will return false if fragments are present.<br/>`allow_query_components` - if set to false isURL will return false if query components are present.<br/>`validate_length` - if set to false isURL will skip string length validation (2083 characters is IE max URL length).
**isUrlResolvable(str)** | check if a giving url is resolvable via DNS. <br/><br/>API <br/><br/> isUrlResolvable(url:string):boolean. <br/><br/> Returns `true` if the given URL is resolvable via DNS. `false` otherwise. <br/> <br/> `url` - The URL to be check is its resolvable. <br/><br/> Usage <br/><br/>const { isUrlResolvable } = require('validator'); <br/><br/>const url = 'https://www.google.com';<br/><br/>if (isUrlResolvable(url)) {<br/><br/> console.log(`${url} is resolvable`);<br/><br/>} <br/><br/>else { <br/><br/> console.log(`${url} is not resolvable`); <br/><br/>}
**isUUID(str [, version])** | check if the string is a UUID (version 1, 2, 3, 4 or 5).
**isVariableWidth(str)** | check if the string contains a mixture of full and half-width chars.
**isVAT(str, countryCode)** | check if the string is a [valid VAT number][VAT Number] if validation is available for the given country code matching [ISO 3166-1 alpha-2][ISO 3166-1 alpha-2]. <br/><br/>`countryCode` is one of `['AL', 'AR', 'AT', 'AU', 'BE', 'BG', 'BO', 'BR', 'BY', 'CA', 'CH', 'CL', 'CO', 'CR', 'CY', 'CZ', 'DE', 'DK', 'DO', 'EC', 'EE', 'EL', 'ES', 'FI', 'FR', 'GB', 'GT', 'HN', 'HR', 'HU', 'ID', 'IE', 'IL', 'IN', 'IS', 'IT', 'KZ', 'LT', 'LU', 'LV', 'MK', 'MT', 'MX', 'NG', 'NI', 'NL', 'NO', 'NZ', 'PA', 'PE', 'PH', 'PL', 'PT', 'PY', 'RO', 'RS', 'RU', 'SA', 'SE', 'SI', 'SK', 'SM', 'SV', 'TR', 'UA', 'UY', 'UZ', 'VE']`.
Expand Down
35 changes: 35 additions & 0 deletions src/lib/isUrlResolvable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* isUrlResolvable Function
* This function takes a URL string as input and checks if the URL is resolvable by performing a DNS lookup on the hostname.
* @param {string} passed_url - The URL string to be checked
* @return {boolean} - Returns true if the URL is resolvable, false otherwise
*/
const isUrlResolvable = function (passed_url) {

// Check if passed url has a protocol
// If not, add 'http://' by default
const urlWithProtocol = passed_url.startsWith('http://') || passed_url.startsWith('https://') ? passed_url : `http://${passed_url}`;

// Parse the URL to extract the hostname
const parsedUrl = new URL(urlWithProtocol);

// Check that the hostname is valid
const hostname = parsedUrl.hostname;
if (!hostname) {
return false;
}

// Attempt to resolve the hostname using DNS lookup
return new Promise((resolve) => {
dns.resolve(hostname, (err, records) => {
if (err) {
resolve(false);
} else {
resolve(true);
}
});
});
};

module.exports = isUrlResolvable;

60 changes: 60 additions & 0 deletions test/validators/isUrlResolvable.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import test from '../testFunctions';

describe('isUrlResolvable', () => {
it('should validate resolvable URLs', () => {
test({
validator: 'isUrlResolvable',
valid: [
'https://www.google.com/',
'https://www.facebook.com/',
'https://www.youtube.com/',
'https://www.reddit.com/',
'https://www.instagram.com/',
'https://www.wikipedia.org/',
'https://www.linkedin.com/',
],
invalid: [
'http://localhost/test.html',
'example.com',
'http://localhost',
'ftp://localhost/test.html',
'https://madeupdomain3456.com',
'https://foo.bar.baz',
'https://..com/',
],
});
});

it('should let users specify whether URLs require a protocol', () => {
test({
validator: 'isUrlResolvable',
args: [{
require_protocol: true,
}],
valid: [
'http://www.example.com/',
'https://www.example.com/',
],
invalid: [
'www.example.com',
'example.com',
],
});
});

it('should let users specify whether subdomains are allowed', () => {
test({
validator: 'isUrlResolvable',
args: [{
allow_subdomains: true,
}],
valid: [
'http://www.example.com/',
'http://subdomain.example.com/',
],
invalid: [
'http://example.com/',
],
});
});
});