How to use the isURL function from validator

Find comprehensive JavaScript validator.isURL code examples handpicked from public code repositorys.

validator.isURL is a function that checks if a given string is a valid URL.

262
263
264
265
266
267
268
269
270
function process_form(input) {
  // check whether the input is a valid URL
  var url = sanitize_url(input)
  .then(function(url) {

    var isURL    = validator.isURL(url, {
      protocols: ['http','https'],
      allow_underscores: true
    });
fork icon42
star icon123
watch icon5

+ 3 other calls in file

2
3
4
5
6
7
8
9
10
11
console.log('foo@bar.com\n', 'isEmail', validator.isEmail('foo@bar.com'));
console.log('https://github.com/chriso/validator.js\n', 'isEmail', validator.isEmail('https://github.com/chriso/validator.js'));


console.log('foo@bar.com\n', 'isURL', validator.isURL('foo@bar.com'));
console.log('https://github.com/chriso/validator.js\n', 'isURL', validator.isURL('https://github.com/chriso/validator.js'));


console.log('127.0.0.1\n', 'isIP', validator.isIP('127.0.0.1'));
console.log('2001:DB8:2de:0:0:0:0:e13\n', 'isIP', validator.isIP('2001:DB8:2de:0:0:0:0:e13'));
fork icon15
star icon3
watch icon4

+ 3 other calls in file

How does validator.isURL work?

validator.isURL is a function that checks whether a given string is a valid URL according to a set of rules defined by the function. It checks the protocol, username, password, hostname, port, pathname, search, and hash components of the URL string to ensure that they meet the requirements of a valid URL.

302
303
304
305
306
307
308
309
310
311
// lookup translation result from cache
const key = `${locale}:${revHash(phrase)}`;
let translation;

// do not translate if it is an email, FQDN, URL, or IP
if (isEmail(phrase) || isFQDN(phrase) || isURL(phrase) || isIP(phrase))
  translation = phrase;
else if (this.redisClient)
  translation = await this.redisClient.get(key);
debug('translation', translation);
fork icon1
star icon11
watch icon0

87
88
89
90
91
92
93
94
95
96
},
fqdn: function(x) {
  check(x, "a domain name", validator.isFQDN(x));
},
url: function(x) {
  check(x, "a URL", validator.isURL(x));
},
email: function(x) {
  check(x, "an email address", validator.isEmail(x));
},
fork icon2
star icon4
watch icon0

Ai Example

1
2
3
4
5
6
const validator = require("validator");

const url = "https://example.com";
const isValidURL = validator.isURL(url);

console.log(isValidURL); // Output: true

In this example, we first import the validator module. We then define a string url that we want to validate as a URL. We call the validator.isURL() method and pass the url variable as an argument. This method returns a boolean value indicating whether the url is a valid URL or not. In this case, it will return true since https://example.com is a valid URL.

207
208
209
210
211
212
213
214
215
216
case 'nat':
  isValid = validator.isInt(stringValue, { min: 0 });
  break;

case 'url':
  isValid = validator.isURL(stringValue, { require_protocol: true });
  break;

case 'alpha':
  isValid = validator.isAlpha(stringValue);
fork icon0
star icon2
watch icon1

+ 31 other calls in file

55
56
57
58
59
60
61
62
63
64
   */
export const isDataURL = (s: string) => !!s.match(/^data:((?:\w+\/(?:(?!;).)+)?)((?:;[\w\W]*?[^;])*),(.+)$/g);

export const isBase64 = (s: string) => /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/.test(s)

export const isUrl = (s: string) => validator.isURL(s)

export const bufferToDataURI = async (buff: Buffer) => {
  const {mime} = await FileType.fromBuffer(buff)
  return `data:${mime};base64,${buff.toString('base64')}`
fork icon2
star icon1
watch icon3

51
52
53
54
55
56
57
58
59
60
'alphadashed': function (x) {return (/^[a-zA-Z-_]*$/).test(x); },
'numeric'       : validator.isNumeric,
'alphanumeric': validator.isAlphanumeric,
'alphanumericdashed': function (x) {return (/^[a-zA-Z0-9-_]*$/).test(x); },
'email'         : validator.isEmail,
'url'           : function(x, opt) { return validator.isURL(x, opt === true ? undefined : opt); },
'urlish'        : /^\s([^\/]+\.)+.+\s*$/g,
'ip'                    : validator.isIP,
'ipv4'          : validator.isIPv4,
'ipv6'          : validator.isIPv6,
fork icon59
star icon0
watch icon7

32
33
34
35
36
37
38
39
40
41
  }
  return true;
},
isURL: function(rule, value) {
  if (rule) {
    return validator.isURL(value);
  }
  return true;
},
isFQDN: function(rule, value) {
fork icon0
star icon2
watch icon2

+ 5 other calls in file

116
117
118
119
120
121
122
123
124
125
// isURL(str [, options]) - check if the string is an URL. options is an object
// which defaults to { protocols: ['http','https','ftp'], require_tld: true,
// require_protocol: false, allow_underscores: false, host_whitelist: false,
// host_blacklist: false, allow_trailing_dot: false, allow_protocol_relative_urls: false }.
isURL: function (str, options) {
  return validator.isURL(str, typeof options === 'object' ? options : undefined);
},
// isUUID(str [, version]) - check if the string is a UUID (version 3, 4 or 5).
isUUID: function (str, version) {
  return validator.isUUID(str, typeof version !== 'boolean' ? version : undefined);
fork icon0
star icon1
watch icon3

+ 17 other calls in file

1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
        // https://github.com/zaggino/z-schema/issues/18
        // RegExp from http://tools.ietf.org/html/rfc3986#appendix-B
        return typeof uri !== "string" || RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?").test(uri);
    },
    "strict-uri": function (uri) {
        return typeof uri !== "string" || validator.isURL(uri);
    }
};


module.exports = FormatValidators;
fork icon0
star icon2
watch icon1

160
161
162
163
164
165
166
167
168
169

if (
  (ignoreCurrency && validator.isCurrency(word)) ||
  (ignoreEmail && validator.isEmail(word)) ||
  (ignoreFqdn && validator.isFQDN(word)) ||
  (ignoreUrl && validator.isURL(word)) ||
  (ignoreUnits && unitFilter.test(word))
) {
  parent.children[index] = {
    type: 'SourceNode',
fork icon0
star icon2
watch icon2

24
25
26
27
28
29
30
31
32
33
34
    }
}


function validateCallbackURL(url) {
    try {
        return isURL(url, {
            protocols: ['http', 'https'],
            require_tld: false,
            require_protocol: true,
            require_host: true,
fork icon25
star icon1
watch icon0

43
44
45
46
47
48
49
50
51
52
  required: true,
  default:
    'http://1.gravatar.com/avatar/1ec59eae354306975b17d78e8473d78b?s=90&d=mm&r=g',
  validate: {
    validator: function (value) {
      return validator.isURL(value)
    },
    message: 'Image not found',
  },
},
fork icon0
star icon0
watch icon1

23
24
25
26
27
28
29
30
31
32
},
image: {
  type: String,
  required: true,
  validate: {
    validator: (v) => validator.isURL(v),
  },
},
trailerLink: {
  type: String,
fork icon0
star icon0
watch icon0

+ 2 other calls in file

68
69
70
71
72
73
74
75
76
77
78
79
validator.extend('isTimezone', function isTimezone(str) {
    return moment.tz.zone(str) ? true : false;
});


validator.extend('isEmptyOrURL', function isEmptyOrURL(str) {
    return (_.isEmpty(str) || validator.isURL(str, {require_protocol: false}));
});


validator.extend('isSlug', function isSlug(str) {
    return validator.matches(str, /^[a-z0-9\-_]+$/);
fork icon0
star icon0
watch icon0

+ 2 other calls in file

9
10
11
12
13
14
15
16
17
18
},
link: {
  type: String,
  required: true,
  validate: {
    validator: (link) => validator.isURL(link),
    message: 'Введите корректный URL',
  },
},
owner: {
fork icon0
star icon0
watch icon0

26
27
28
29
30
31
32
33
34
35
36
37
    return validator.isDate(date);
}


// Validate URL
exports.validateURL = (url) => {
    return validator.isURL(url);
}


// Validate IP address

fork icon0
star icon0
watch icon0

58
59
60
61
62
63
64
65
66
67
  .isEmpty()
  .withMessage('IS_EMPTY')
  .trim(),
check('urlTwitter')
  .optional()
  .custom(v => (v === '' ? true : validator.isURL(v)))
  .withMessage('NOT_A_VALID_URL'),
check('urlGitHub')
  .optional()
  .custom(v => (v === '' ? true : validator.isURL(v)))
fork icon0
star icon0
watch icon0

+ 3 other calls in file

99
100
101
102
103
104
105
106
107
108
}
if (req.body.role) {
    isRole = validator.matches(String(role), regExText);
}
if (req.body.linkedin_url) {
    isLinkedinUrl = validator.isURL(String(linkedin_url), [["http", "https"]]);
}

if (isFirstName && isLastName && isEmail && isDepartment && isRole && isLinkedinUrl) {
    const string =
fork icon0
star icon0
watch icon0

200
201
202
203
204
205
206
207
208
209
function ifExistsIsUrl(location, fieldName, message) {
  const validator = getFunctionName(location);
  return validator(fieldName)
    .custom((paramFieldName) => {
      if (hf.isEmptyValue(paramFieldName)) return true;
      return validatorLibrary.isURL(paramFieldName);
    })
    .withMessage(message);
}
/**
fork icon0
star icon0
watch icon0