-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
74 lines (62 loc) · 1.96 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
'use strict'
const url = require('url')
const tld = require('tldjs')
const ipAddress = require('ip-address')
const emailRE = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[A-Za-z]{2,}$/
const EMAIL_NAME_RE = new RegExp(
'^[a-z \\d!#\\$%&\'\\*\\+\\-\\/=\\?\\^_"`{\\|\\,\\(\\)@'
+ '}~\\.\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]*'
+ '<(.+)>$', 'i'
)
const uuidRE = new RegExp('^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]' +
'{3}-[89ABab][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$')
const dateRE = new RegExp('^[\\d]{4}-[\\d]{2}-[\\d]{2}T[\\d]{2}:[\\d]{2}:' +
'[\\d]{2}(\.[\\d]{1,3})?(Z|[\\+\\-][\\d]{2}:[\\d]{2})$')
const protocols = new Set([
'http:'
, 'https:'
])
exports.isDate = function isDate(d) {
if (!d) return false
if (typeof d === 'object' && d.toISOString) {
return dateRE.test(d.toISOString())
}
return dateRE.test(d)
}
exports.isEmail = function isEmail(s) {
try {
if (typeof s !== 'string') return false
if (s.length >= 255) return false
const isEmail = tld.tldExists(s) && emailRE.test(s)
return isEmail
} catch (err) {
return false
}
}
exports.isEmailAllowName = function isEmailAllowName(s) {
if (typeof s !== 'string') return false
const match = s.match(EMAIL_NAME_RE)
if (match) {
return exports.isEmail(match[1])
}
return exports.isEmail(s)
}
// TODO(evanlucas) benchmark the difference between the current implementation
// and using a a custom implementation.
exports.isUUID = function isUUID(s) {
if (typeof s !== 'string') return false
if (s.length !== 36) return false
return uuidRE.test(s)
}
exports.isUrl = function isUrl(s) {
if (typeof s !== 'string') return false
const u = url.parse(s)
return protocols.has(u.protocol) && !!u.host && !!u.path
}
exports.isIpAllowCIDR = function isIpAllowCIDR(s) {
if (typeof s !== 'string') return false
const IpAddressType = s.indexOf(':') > -1
? ipAddress.Address6 : ipAddress.Address4
const address = new IpAddressType(s)
return address.isValid()
}