validator
Version:
String validation and sanitization
1,517 lines (1,424 loc) • 196 kB
JavaScript
/*!
* Copyright (c) 2018 Chris O'Hara <cohara87@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.validator = factory());
}(this, (function () { 'use strict';
function _arrayLikeToArray(r, a) {
(null == a || a > r.length) && (a = r.length);
for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
return n;
}
function _arrayWithHoles(r) {
if (Array.isArray(r)) return r;
}
function _arrayWithoutHoles(r) {
if (Array.isArray(r)) return _arrayLikeToArray(r);
}
function _createForOfIteratorHelper(r, e) {
var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (!t) {
if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
t && (r = t);
var n = 0,
F = function () {};
return {
s: F,
n: function () {
return n >= r.length ? {
done: !0
} : {
done: !1,
value: r[n++]
};
},
e: function (r) {
throw r;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var o,
a = !0,
u = !1;
return {
s: function () {
t = t.call(r);
},
n: function () {
var r = t.next();
return a = r.done, r;
},
e: function (r) {
u = !0, o = r;
},
f: function () {
try {
a || null == t.return || t.return();
} finally {
if (u) throw o;
}
}
};
}
function _iterableToArray(r) {
if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
}
function _iterableToArrayLimit(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = !0,
o = !1;
try {
if (i = (t = t.call(r)).next, 0 === l) {
if (Object(t) !== t) return;
f = !1;
} else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
} catch (r) {
o = !0, n = r;
} finally {
try {
if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
} finally {
if (o) throw n;
}
}
return a;
}
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _setFunctionName(e, t, n) {
"symbol" == typeof t && (t = (t = t.description) ? "[" + t + "]" : "");
try {
Object.defineProperty(e, "name", {
configurable: !0,
value: n ? n + " " + t : t
});
} catch (e) {}
return e;
}
function _slicedToArray(r, e) {
return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _toConsumableArray(r) {
return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
}
function _toPrimitive(t, r) {
if ("object" != typeof t || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != typeof i) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
function _toPropertyKey(t) {
var i = _toPrimitive(t, "string");
return "symbol" == typeof i ? i : i + "";
}
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
function _unsupportedIterableToArray(r, a) {
if (r) {
if ("string" == typeof r) return _arrayLikeToArray(r, a);
var t = {}.toString.call(r).slice(8, -1);
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
}
}
function old_createMetadataMethodsForProperty(e, t, a, r) {
return {
getMetadata: function (o) {
old_assertNotFinished(r, "getMetadata"), old_assertMetadataKey(o);
var i = e[o];
if (void 0 !== i) if (1 === t) {
var n = i.public;
if (void 0 !== n) return n[a];
} else if (2 === t) {
var l = i.private;
if (void 0 !== l) return l.get(a);
} else if (Object.hasOwnProperty.call(i, "constructor")) return i.constructor;
},
setMetadata: function (o, i) {
old_assertNotFinished(r, "setMetadata"), old_assertMetadataKey(o);
var n = e[o];
if (void 0 === n && (n = e[o] = {}), 1 === t) {
var l = n.public;
void 0 === l && (l = n.public = {}), l[a] = i;
} else if (2 === t) {
var s = n.priv;
void 0 === s && (s = n.private = new Map()), s.set(a, i);
} else n.constructor = i;
}
};
}
function old_createAddInitializerMethod(e, t) {
return function (a) {
old_assertNotFinished(t, "addInitializer"), old_assertCallable(a, "An initializer"), e.push(a);
};
}
function old_memberDec(e, t, a, r, o, i, n, l, s) {
var c;
switch (i) {
case 1:
c = "accessor";
break;
case 2:
c = "method";
break;
case 3:
c = "getter";
break;
case 4:
c = "setter";
break;
default:
c = "field";
}
var d,
u,
f = {
kind: c,
name: l ? "#" + t : _toPropertyKey(t),
isStatic: n,
isPrivate: l
},
p = {
v: !1
};
if (0 !== i && (f.addInitializer = old_createAddInitializerMethod(o, p)), l) {
d = 2, u = Symbol(t);
var v = {};
0 === i ? (v.get = a.get, v.set = a.set) : 2 === i ? v.get = function () {
return a.value;
} : (1 !== i && 3 !== i || (v.get = function () {
return a.get.call(this);
}), 1 !== i && 4 !== i || (v.set = function (e) {
a.set.call(this, e);
})), f.access = v;
} else d = 1, u = t;
try {
return e(s, Object.assign(f, old_createMetadataMethodsForProperty(r, d, u, p)));
} finally {
p.v = !0;
}
}
function old_assertNotFinished(e, t) {
if (e.v) throw Error("attempted to call " + t + " after decoration was finished");
}
function old_assertMetadataKey(e) {
if ("symbol" != typeof e) throw new TypeError("Metadata keys must be symbols, received: " + e);
}
function old_assertCallable(e, t) {
if ("function" != typeof e) throw new TypeError(t + " must be a function");
}
function old_assertValidReturnValue(e, t) {
var a = typeof t;
if (1 === e) {
if ("object" !== a || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
void 0 !== t.get && old_assertCallable(t.get, "accessor.get"), void 0 !== t.set && old_assertCallable(t.set, "accessor.set"), void 0 !== t.init && old_assertCallable(t.init, "accessor.init"), void 0 !== t.initializer && old_assertCallable(t.initializer, "accessor.initializer");
} else if ("function" !== a) throw new TypeError((0 === e ? "field" : 10 === e ? "class" : "method") + " decorators must return a function or void 0");
}
function old_getInit(e) {
var t;
return null == (t = e.init) && (t = e.initializer) && void 0 !== console && console.warn(".initializer has been renamed to .init as of March 2022"), t;
}
function assertString(input) {
var isString = typeof input === 'string' || input instanceof String;
if (!isString) {
var invalidType = _typeof(input);
if (input === null) invalidType = 'null';else if (invalidType === 'object') invalidType = input.constructor.name;
throw new TypeError("Expected a string but received a ".concat(invalidType));
}
}
function toDate(date) {
assertString(date);
date = Date.parse(date);
return !isNaN(date) ? new Date(date) : null;
}
function isNullOrUndefined(value) {
return value === null || value === undefined;
}
var alpha = {
'en-US': /^[A-Z]+$/i,
'az-AZ': /^[A-VXYZÇƏĞİıÖŞÜ]+$/i,
'bg-BG': /^[А-Я]+$/i,
'cs-CZ': /^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,
'da-DK': /^[A-ZÆØÅ]+$/i,
'de-DE': /^[A-ZÄÖÜß]+$/i,
'el-GR': /^[Α-ώ]+$/i,
'es-ES': /^[A-ZÁÉÍÑÓÚÜ]+$/i,
'fa-IR': /^[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهی]+$/i,
'fi-FI': /^[A-ZÅÄÖ]+$/i,
'fr-FR': /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,
'it-IT': /^[A-ZÀÉÈÌÎÓÒÙ]+$/i,
'ja-JP': /^[ぁ-んァ-ヶヲ-゚一-龠ー・。、]+$/i,
'nb-NO': /^[A-ZÆØÅ]+$/i,
'nl-NL': /^[A-ZÁÉËÏÓÖÜÚ]+$/i,
'nn-NO': /^[A-ZÆØÅ]+$/i,
'hu-HU': /^[A-ZÁÉÍÓÖŐÚÜŰ]+$/i,
'pl-PL': /^[A-ZĄĆĘŚŁŃÓŻŹ]+$/i,
'pt-PT': /^[A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$/i,
'ru-RU': /^[А-ЯЁ]+$/i,
'kk-KZ': /^[А-ЯЁ\u04D8\u04B0\u0406\u04A2\u0492\u04AE\u049A\u04E8\u04BA]+$/i,
'sl-SI': /^[A-ZČĆĐŠŽ]+$/i,
'sk-SK': /^[A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,
'sr-RS@latin': /^[A-ZČĆŽŠĐ]+$/i,
'sr-RS': /^[А-ЯЂЈЉЊЋЏ]+$/i,
'sv-SE': /^[A-ZÅÄÖ]+$/i,
'th-TH': /^[ก-๐\s]+$/i,
'tr-TR': /^[A-ZÇĞİıÖŞÜ]+$/i,
'uk-UA': /^[А-ЩЬЮЯЄIЇҐі]+$/i,
'vi-VN': /^[A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$/i,
'ko-KR': /^[ㄱ-ㅎㅏ-ㅣ가-힣]*$/,
'ku-IQ': /^[ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i,
ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/,
he: /^[א-ת]+$/,
fa: /^['آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی']+$/i,
bn: /^['ঀঁংঃঅআইঈউঊঋঌএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহ়ঽািীুূৃৄেৈোৌ্ৎৗড়ঢ়য়ৠৡৢৣৰৱ৲৳৴৵৶৷৸৹৺৻']+$/,
eo: /^[ABCĈD-GĜHĤIJĴK-PRSŜTUŬVZ]+$/i,
'hi-IN': /^[\u0900-\u0961]+[\u0972-\u097F]*$/i,
'si-LK': /^[\u0D80-\u0DFF]+$/
};
var alphanumeric = {
'en-US': /^[0-9A-Z]+$/i,
'az-AZ': /^[0-9A-VXYZÇƏĞİıÖŞÜ]+$/i,
'bg-BG': /^[0-9А-Я]+$/i,
'cs-CZ': /^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,
'da-DK': /^[0-9A-ZÆØÅ]+$/i,
'de-DE': /^[0-9A-ZÄÖÜß]+$/i,
'el-GR': /^[0-9Α-ω]+$/i,
'es-ES': /^[0-9A-ZÁÉÍÑÓÚÜ]+$/i,
'fi-FI': /^[0-9A-ZÅÄÖ]+$/i,
'fr-FR': /^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,
'it-IT': /^[0-9A-ZÀÉÈÌÎÓÒÙ]+$/i,
'ja-JP': /^[0-90-9ぁ-んァ-ヶヲ-゚一-龠ー・。、]+$/i,
'hu-HU': /^[0-9A-ZÁÉÍÓÖŐÚÜŰ]+$/i,
'nb-NO': /^[0-9A-ZÆØÅ]+$/i,
'nl-NL': /^[0-9A-ZÁÉËÏÓÖÜÚ]+$/i,
'nn-NO': /^[0-9A-ZÆØÅ]+$/i,
'pl-PL': /^[0-9A-ZĄĆĘŚŁŃÓŻŹ]+$/i,
'pt-PT': /^[0-9A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$/i,
'ru-RU': /^[0-9А-ЯЁ]+$/i,
'kk-KZ': /^[0-9А-ЯЁ\u04D8\u04B0\u0406\u04A2\u0492\u04AE\u049A\u04E8\u04BA]+$/i,
'sl-SI': /^[0-9A-ZČĆĐŠŽ]+$/i,
'sk-SK': /^[0-9A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,
'sr-RS@latin': /^[0-9A-ZČĆŽŠĐ]+$/i,
'sr-RS': /^[0-9А-ЯЂЈЉЊЋЏ]+$/i,
'sv-SE': /^[0-9A-ZÅÄÖ]+$/i,
'th-TH': /^[ก-๙\s]+$/i,
'tr-TR': /^[0-9A-ZÇĞİıÖŞÜ]+$/i,
'uk-UA': /^[0-9А-ЩЬЮЯЄIЇҐі]+$/i,
'ko-KR': /^[0-9ㄱ-ㅎㅏ-ㅣ가-힣]*$/,
'ku-IQ': /^[٠١٢٣٤٥٦٧٨٩0-9ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i,
'vi-VN': /^[0-9A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$/i,
ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/,
he: /^[0-9א-ת]+$/,
fa: /^['0-9آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی۱۲۳۴۵۶۷۸۹۰']+$/i,
bn: /^['ঀঁংঃঅআইঈউঊঋঌএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহ়ঽািীুূৃৄেৈোৌ্ৎৗড়ঢ়য়ৠৡৢৣ০১২৩৪৫৬৭৮৯ৰৱ৲৳৴৵৶৷৸৹৺৻']+$/,
eo: /^[0-9ABCĈD-GĜHĤIJĴK-PRSŜTUŬVZ]+$/i,
'hi-IN': /^[\u0900-\u0963]+[\u0966-\u097F]*$/i,
'si-LK': /^[0-9\u0D80-\u0DFF]+$/
};
var decimal = {
'en-US': '.',
ar: '٫'
};
var englishLocales = ['AU', 'GB', 'HK', 'IN', 'NZ', 'ZA', 'ZM'];
for (var locale, i = 0; i < englishLocales.length; i++) {
locale = "en-".concat(englishLocales[i]);
alpha[locale] = alpha['en-US'];
alphanumeric[locale] = alphanumeric['en-US'];
decimal[locale] = decimal['en-US'];
}
// Source: http://www.localeplanet.com/java/
var arabicLocales = ['AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'QM', 'QA', 'SA', 'SD', 'SY', 'TN', 'YE'];
for (var _locale, _i = 0; _i < arabicLocales.length; _i++) {
_locale = "ar-".concat(arabicLocales[_i]);
alpha[_locale] = alpha.ar;
alphanumeric[_locale] = alphanumeric.ar;
decimal[_locale] = decimal.ar;
}
var farsiLocales = ['IR', 'AF'];
for (var _locale2, _i2 = 0; _i2 < farsiLocales.length; _i2++) {
_locale2 = "fa-".concat(farsiLocales[_i2]);
alphanumeric[_locale2] = alphanumeric.fa;
decimal[_locale2] = decimal.ar;
}
var bengaliLocales = ['BD', 'IN'];
for (var _locale3, _i3 = 0; _i3 < bengaliLocales.length; _i3++) {
_locale3 = "bn-".concat(bengaliLocales[_i3]);
alpha[_locale3] = alpha.bn;
alphanumeric[_locale3] = alphanumeric.bn;
decimal[_locale3] = decimal['en-US'];
}
// Source: https://en.wikipedia.org/wiki/Decimal_mark
var dotDecimal = ['ar-EG', 'ar-LB', 'ar-LY'];
var commaDecimal = ['bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-ZM', 'eo', 'es-ES', 'fr-CA', 'fr-FR', 'id-ID', 'it-IT', 'ku-IQ', 'hi-IN', 'hu-HU', 'nb-NO', 'nn-NO', 'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'kk-KZ', 'si-LK', 'sl-SI', 'sr-RS@latin', 'sr-RS', 'sv-SE', 'tr-TR', 'uk-UA', 'vi-VN'];
for (var _i4 = 0; _i4 < dotDecimal.length; _i4++) {
decimal[dotDecimal[_i4]] = decimal['en-US'];
}
for (var _i5 = 0; _i5 < commaDecimal.length; _i5++) {
decimal[commaDecimal[_i5]] = ',';
}
alpha['fr-CA'] = alpha['fr-FR'];
alphanumeric['fr-CA'] = alphanumeric['fr-FR'];
alpha['pt-BR'] = alpha['pt-PT'];
alphanumeric['pt-BR'] = alphanumeric['pt-PT'];
decimal['pt-BR'] = decimal['pt-PT'];
// see #862
alpha['pl-Pl'] = alpha['pl-PL'];
alphanumeric['pl-Pl'] = alphanumeric['pl-PL'];
decimal['pl-Pl'] = decimal['pl-PL'];
// see #1455
alpha['fa-AF'] = alpha.fa;
function isFloat(str, options) {
assertString(str);
options = options || {};
var _float = new RegExp("^(?:[-+])?(?:[0-9]+)?(?:\\".concat(options.locale ? decimal[options.locale] : '.', "[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$"));
if (str === '' || str === '.' || str === ',' || str === '-' || str === '+') {
return false;
}
var value = parseFloat(str.replace(',', '.'));
return _float.test(str) && (!options.hasOwnProperty('min') || isNullOrUndefined(options.min) || value >= options.min) && (!options.hasOwnProperty('max') || isNullOrUndefined(options.max) || value <= options.max) && (!options.hasOwnProperty('lt') || isNullOrUndefined(options.lt) || value < options.lt) && (!options.hasOwnProperty('gt') || isNullOrUndefined(options.gt) || value > options.gt);
}
var locales = Object.keys(decimal);
function toFloat(str) {
if (!isFloat(str)) return NaN;
return parseFloat(str);
}
function toInt(str, radix) {
assertString(str);
return parseInt(str, radix || 10);
}
function toBoolean(str, strict) {
assertString(str);
if (strict) {
return str === '1' || /^true$/i.test(str);
}
return str !== '0' && !/^false$/i.test(str) && str !== '';
}
function equals(str, comparison) {
assertString(str);
return str === comparison;
}
function toString$1(input) {
if (_typeof(input) === 'object' && input !== null) {
if (typeof input.toString === 'function') {
input = input.toString();
} else {
input = '[object Object]';
}
} else if (input === null || typeof input === 'undefined' || isNaN(input) && !input.length) {
input = '';
}
return String(input);
}
function merge() {
var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var defaults = arguments.length > 1 ? arguments[1] : undefined;
for (var key in defaults) {
if (typeof obj[key] === 'undefined') {
obj[key] = defaults[key];
}
}
return obj;
}
var defaultContainsOptions = {
ignoreCase: false,
minOccurrences: 1
};
function contains(str, elem, options) {
assertString(str);
options = merge(options, defaultContainsOptions);
if (options.ignoreCase) {
return str.toLowerCase().split(toString$1(elem).toLowerCase()).length > options.minOccurrences;
}
return str.split(toString$1(elem)).length > options.minOccurrences;
}
function matches(str, pattern, modifiers) {
assertString(str);
if (Object.prototype.toString.call(pattern) !== '[object RegExp]') {
pattern = new RegExp(pattern, modifiers);
}
return !!str.match(pattern);
}
function isRegExp(obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
}
function checkHost(host, matches) {
for (var i = 0; i < matches.length; i++) {
var match = matches[i];
if (host === match || isRegExp(match) && match.test(host)) {
return true;
}
}
return false;
}
/* eslint-disable prefer-rest-params */
function isByteLength(str, options) {
assertString(str);
var min;
var max;
if (_typeof(options) === 'object') {
min = options.min || 0;
max = options.max;
} else {
// backwards compatibility: isByteLength(str, min [, max])
min = arguments[1];
max = arguments[2];
}
var len = encodeURI(str).split(/%..|./).length - 1;
return len >= min && (typeof max === 'undefined' || len <= max);
}
var default_fqdn_options = {
require_tld: true,
allow_underscores: false,
allow_trailing_dot: false,
allow_numeric_tld: false,
allow_wildcard: false,
ignore_max_length: false
};
function isFQDN(str, options) {
assertString(str);
options = merge(options, default_fqdn_options);
/* Remove the optional trailing dot before checking validity */
if (options.allow_trailing_dot && str[str.length - 1] === '.') {
str = str.substring(0, str.length - 1);
}
/* Remove the optional wildcard before checking validity */
if (options.allow_wildcard === true && str.indexOf('*.') === 0) {
str = str.substring(2);
}
var parts = str.split('.');
var tld = parts[parts.length - 1];
if (options.require_tld) {
// disallow fqdns without tld
if (parts.length < 2) {
return false;
}
if (!options.allow_numeric_tld && !/^([a-z\u00A1-\u00A8\u00AA-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) {
return false;
}
// disallow spaces
if (/\s/.test(tld)) {
return false;
}
}
// reject numeric TLDs
if (!options.allow_numeric_tld && /^\d+$/.test(tld)) {
return false;
}
return parts.every(function (part) {
if (part.length > 63 && !options.ignore_max_length) {
return false;
}
if (!/^[a-z_\u00a1-\uffff0-9-]+$/i.test(part)) {
return false;
}
// disallow full-width chars
if (/[\uff01-\uff5e]/.test(part)) {
return false;
}
// disallow parts starting or ending with hyphen
if (/^-|-$/.test(part)) {
return false;
}
if (!options.allow_underscores && /_/.test(part)) {
return false;
}
return true;
});
}
/**
11.3. Examples
The following addresses
fe80::1234 (on the 1st link of the node)
ff02::5678 (on the 5th link of the node)
ff08::9abc (on the 10th organization of the node)
would be represented as follows:
fe80::1234%1
ff02::5678%5
ff08::9abc%10
(Here we assume a natural translation from a zone index to the
<zone_id> part, where the Nth zone of any scope is translated into
"N".)
If we use interface names as <zone_id>, those addresses could also be
represented as follows:
fe80::1234%ne0
ff02::5678%pvc1.3
ff08::9abc%interface10
where the interface "ne0" belongs to the 1st link, "pvc1.3" belongs
to the 5th link, and "interface10" belongs to the 10th organization.
* * */
var IPv4SegmentFormat = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
var IPv4AddressFormat = "(".concat(IPv4SegmentFormat, "[.]){3}").concat(IPv4SegmentFormat);
var IPv4AddressRegExp = new RegExp("^".concat(IPv4AddressFormat, "$"));
var IPv6SegmentFormat = '(?:[0-9a-fA-F]{1,4})';
var IPv6AddressRegExp = new RegExp('^(' + "(?:".concat(IPv6SegmentFormat, ":){7}(?:").concat(IPv6SegmentFormat, "|:)|") + "(?:".concat(IPv6SegmentFormat, ":){6}(?:").concat(IPv4AddressFormat, "|:").concat(IPv6SegmentFormat, "|:)|") + "(?:".concat(IPv6SegmentFormat, ":){5}(?::").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,2}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){4}(?:(:").concat(IPv6SegmentFormat, "){0,1}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,3}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){3}(?:(:").concat(IPv6SegmentFormat, "){0,2}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,4}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){2}(?:(:").concat(IPv6SegmentFormat, "){0,3}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,5}|:)|") + "(?:".concat(IPv6SegmentFormat, ":){1}(?:(:").concat(IPv6SegmentFormat, "){0,4}:").concat(IPv4AddressFormat, "|(:").concat(IPv6SegmentFormat, "){1,6}|:)|") + "(?::((?::".concat(IPv6SegmentFormat, "){0,5}:").concat(IPv4AddressFormat, "|(?::").concat(IPv6SegmentFormat, "){1,7}|:))") + ')(%[0-9a-zA-Z-.:]{1,})?$');
function isIP(str) {
var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
assertString(str);
version = String(version);
if (!version) {
return isIP(str, 4) || isIP(str, 6);
}
if (version === '4') {
return IPv4AddressRegExp.test(str);
}
if (version === '6') {
return IPv6AddressRegExp.test(str);
}
return false;
}
var default_email_options = {
allow_display_name: false,
allow_underscores: false,
require_display_name: false,
allow_utf8_local_part: true,
require_tld: true,
blacklisted_chars: '',
ignore_max_length: false,
host_blacklist: [],
host_whitelist: []
};
/* eslint-disable max-len */
/* eslint-disable no-control-regex */
var splitNameAddress = /^([^\x00-\x1F\x7F-\x9F\cX]+)</i;
var emailUserPart = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i;
var gmailUserPart = /^[a-z\d]+$/;
var quotedEmailUser = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i;
var emailUserUtf8Part = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A1-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$/i;
var quotedEmailUserUtf8 = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*$/i;
var defaultMaxEmailLength = 254;
/* eslint-enable max-len */
/* eslint-enable no-control-regex */
/**
* Validate display name according to the RFC2822: https://tools.ietf.org/html/rfc2822#appendix-A.1.2
* @param {String} display_name
*/
function validateDisplayName(display_name) {
var display_name_without_quotes = display_name.replace(/^"(.+)"$/, '$1');
// display name with only spaces is not valid
if (!display_name_without_quotes.trim()) {
return false;
}
// check whether display name contains illegal character
var contains_illegal = /[\.";<>]/.test(display_name_without_quotes);
if (contains_illegal) {
// if contains illegal characters,
// must to be enclosed in double-quotes, otherwise it's not a valid display name
if (display_name_without_quotes === display_name) {
return false;
}
// the quotes in display name must start with character symbol \
var all_start_with_back_slash = display_name_without_quotes.split('"').length === display_name_without_quotes.split('\\"').length;
if (!all_start_with_back_slash) {
return false;
}
}
return true;
}
function isEmail(str, options) {
assertString(str);
options = merge(options, default_email_options);
if (options.require_display_name || options.allow_display_name) {
var display_email = str.match(splitNameAddress);
if (display_email) {
var display_name = display_email[1];
// Remove display name and angle brackets to get email address
// Can be done in the regex but will introduce a ReDOS (See #1597 for more info)
str = str.replace(display_name, '').replace(/(^<|>$)/g, '');
// sometimes need to trim the last space to get the display name
// because there may be a space between display name and email address
// eg. myname <address@gmail.com>
// the display name is `myname` instead of `myname `, so need to trim the last space
if (display_name.endsWith(' ')) {
display_name = display_name.slice(0, -1);
}
if (!validateDisplayName(display_name)) {
return false;
}
} else if (options.require_display_name) {
return false;
}
}
if (!options.ignore_max_length && str.length > defaultMaxEmailLength) {
return false;
}
var parts = str.split('@');
var domain = parts.pop();
var lower_domain = domain.toLowerCase();
if (options.host_blacklist.length > 0 && checkHost(lower_domain, options.host_blacklist)) {
return false;
}
if (options.host_whitelist.length > 0 && !checkHost(lower_domain, options.host_whitelist)) {
return false;
}
var user = parts.join('@');
if (options.domain_specific_validation && (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com')) {
/*
Previously we removed dots for gmail addresses before validating.
This was removed because it allows `multiple..dots@gmail.com`
to be reported as valid, but it is not.
Gmail only normalizes single dots, removing them from here is pointless,
should be done in normalizeEmail
*/
user = user.toLowerCase();
// Removing sub-address from username before gmail validation
var username = user.split('+')[0];
// Dots are not included in gmail length restriction
if (!isByteLength(username.replace(/\./g, ''), {
min: 6,
max: 30
})) {
return false;
}
var _user_parts = username.split('.');
for (var i = 0; i < _user_parts.length; i++) {
if (!gmailUserPart.test(_user_parts[i])) {
return false;
}
}
}
if (options.ignore_max_length === false && (!isByteLength(user, {
max: 64
}) || !isByteLength(domain, {
max: 254
}))) {
return false;
}
if (!isFQDN(domain, {
require_tld: options.require_tld,
ignore_max_length: options.ignore_max_length,
allow_underscores: options.allow_underscores
})) {
if (!options.allow_ip_domain) {
return false;
}
if (!isIP(domain)) {
if (!domain.startsWith('[') || !domain.endsWith(']')) {
return false;
}
var noBracketdomain = domain.slice(1, -1);
if (noBracketdomain.length === 0 || !isIP(noBracketdomain)) {
return false;
}
}
}
if (options.blacklisted_chars) {
if (user.search(new RegExp("[".concat(options.blacklisted_chars, "]+"), 'g')) !== -1) return false;
}
if (user[0] === '"' && user[user.length - 1] === '"') {
user = user.slice(1, user.length - 1);
return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user);
}
var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart;
var user_parts = user.split('.');
for (var _i = 0; _i < user_parts.length; _i++) {
if (!pattern.test(user_parts[_i])) {
return false;
}
}
return true;
}
/*
options for isURL method
require_protocol - if set as true isURL will return false if protocol is not present in the URL
require_valid_protocol - isURL will check if the URL's protocol is present in the protocols option
protocols - valid protocols can be modified with this option
require_host - if set as false isURL will not check if host is present in the URL
require_port - if set as true isURL will check if port is present in the URL
allow_protocol_relative_urls - if set as true protocol relative URLs will be allowed
validate_length - if set as false isURL will skip string length validation
max_allowed_length will be ignored if this is set as false
max_allowed_length - if set isURL will not allow URLs longer than max_allowed_length
default is 2084 that IE maximum URL length
*/
var default_url_options = {
protocols: ['http', 'https', 'ftp'],
require_tld: true,
require_protocol: false,
require_host: true,
require_port: false,
require_valid_protocol: true,
allow_underscores: false,
allow_trailing_dot: false,
allow_protocol_relative_urls: false,
allow_fragments: true,
allow_query_components: true,
validate_length: true,
max_allowed_length: 2084
};
var wrapped_ipv6 = /^\[([^\]]+)\](?::([0-9]+))?$/;
function isURL(url, options) {
assertString(url);
if (!url || /[\s<>]/.test(url)) {
return false;
}
if (url.indexOf('mailto:') === 0) {
return false;
}
options = merge(options, default_url_options);
if (options.validate_length && url.length > options.max_allowed_length) {
return false;
}
if (!options.allow_fragments && url.includes('#')) {
return false;
}
if (!options.allow_query_components && (url.includes('?') || url.includes('&'))) {
return false;
}
var protocol, auth, host, hostname, port, port_str, split, ipv6;
split = url.split('#');
url = split.shift();
split = url.split('?');
url = split.shift();
split = url.split('://');
if (split.length > 1) {
protocol = split.shift().toLowerCase();
if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) {
return false;
}
} else if (options.require_protocol) {
return false;
} else if (url.slice(0, 2) === '//') {
if (!options.allow_protocol_relative_urls) {
return false;
}
split[0] = url.slice(2);
}
url = split.join('://');
if (url === '') {
return false;
}
split = url.split('/');
url = split.shift();
if (url === '' && !options.require_host) {
return true;
}
split = url.split('@');
if (split.length > 1) {
if (options.disallow_auth) {
return false;
}
if (split[0] === '') {
return false;
}
auth = split.shift();
if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) {
return false;
}
var _auth$split = auth.split(':'),
_auth$split2 = _slicedToArray(_auth$split, 2),
user = _auth$split2[0],
password = _auth$split2[1];
if (user === '' && password === '') {
return false;
}
}
hostname = split.join('@');
port_str = null;
ipv6 = null;
var ipv6_match = hostname.match(wrapped_ipv6);
if (ipv6_match) {
host = '';
ipv6 = ipv6_match[1];
port_str = ipv6_match[2] || null;
} else {
split = hostname.split(':');
host = split.shift();
if (split.length) {
port_str = split.join(':');
}
}
if (port_str !== null && port_str.length > 0) {
port = parseInt(port_str, 10);
if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) {
return false;
}
} else if (options.require_port) {
return false;
}
if (options.host_whitelist) {
return checkHost(host, options.host_whitelist);
}
if (host === '' && !options.require_host) {
return true;
}
if (!isIP(host) && !isFQDN(host, options) && (!ipv6 || !isIP(ipv6, 6))) {
return false;
}
host = host || ipv6;
if (options.host_blacklist && checkHost(host, options.host_blacklist)) {
return false;
}
return true;
}
var macAddress48 = /^(?:[0-9a-fA-F]{2}([-:\s]))([0-9a-fA-F]{2}\1){4}([0-9a-fA-F]{2})$/;
var macAddress48NoSeparators = /^([0-9a-fA-F]){12}$/;
var macAddress48WithDots = /^([0-9a-fA-F]{4}\.){2}([0-9a-fA-F]{4})$/;
var macAddress64 = /^(?:[0-9a-fA-F]{2}([-:\s]))([0-9a-fA-F]{2}\1){6}([0-9a-fA-F]{2})$/;
var macAddress64NoSeparators = /^([0-9a-fA-F]){16}$/;
var macAddress64WithDots = /^([0-9a-fA-F]{4}\.){3}([0-9a-fA-F]{4})$/;
function isMACAddress(str, options) {
assertString(str);
if (options !== null && options !== void 0 && options.eui) {
options.eui = String(options.eui);
}
/**
* @deprecated `no_colons` TODO: remove it in the next major
*/
if (options !== null && options !== void 0 && options.no_colons || options !== null && options !== void 0 && options.no_separators) {
if (options.eui === '48') {
return macAddress48NoSeparators.test(str);
}
if (options.eui === '64') {
return macAddress64NoSeparators.test(str);
}
return macAddress48NoSeparators.test(str) || macAddress64NoSeparators.test(str);
}
if ((options === null || options === void 0 ? void 0 : options.eui) === '48') {
return macAddress48.test(str) || macAddress48WithDots.test(str);
}
if ((options === null || options === void 0 ? void 0 : options.eui) === '64') {
return macAddress64.test(str) || macAddress64WithDots.test(str);
}
return isMACAddress(str, {
eui: '48'
}) || isMACAddress(str, {
eui: '64'
});
}
var subnetMaybe = /^\d{1,3}$/;
var v4Subnet = 32;
var v6Subnet = 128;
function isIPRange(str) {
var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
assertString(str);
var parts = str.split('/');
// parts[0] -> ip, parts[1] -> subnet
if (parts.length !== 2) {
return false;
}
if (!subnetMaybe.test(parts[1])) {
return false;
}
// Disallow preceding 0 i.e. 01, 02, ...
if (parts[1].length > 1 && parts[1].startsWith('0')) {
return false;
}
var isValidIP = isIP(parts[0], version);
if (!isValidIP) {
return false;
}
// Define valid subnet according to IP's version
var expectedSubnet = null;
switch (String(version)) {
case '4':
expectedSubnet = v4Subnet;
break;
case '6':
expectedSubnet = v6Subnet;
break;
default:
expectedSubnet = isIP(parts[0], '6') ? v6Subnet : v4Subnet;
}
return parts[1] <= expectedSubnet && parts[1] >= 0;
}
var default_date_options = {
format: 'YYYY/MM/DD',
delimiters: ['/', '-'],
strictMode: false
};
function isValidFormat(format) {
return /(^(y{4}|y{2})[.\/-](m{1,2})[.\/-](d{1,2})$)|(^(m{1,2})[.\/-](d{1,2})[.\/-]((y{4}|y{2})$))|(^(d{1,2})[.\/-](m{1,2})[.\/-]((y{4}|y{2})$))/gi.test(format);
}
function zip(date, format) {
var zippedArr = [],
len = Math.max(date.length, format.length);
for (var i = 0; i < len; i++) {
zippedArr.push([date[i], format[i]]);
}
return zippedArr;
}
function isDate(input, options) {
if (typeof options === 'string') {
// Allow backward compatibility for old format isDate(input [, format])
options = merge({
format: options
}, default_date_options);
} else {
options = merge(options, default_date_options);
}
if (typeof input === 'string' && isValidFormat(options.format)) {
if (options.strictMode && input.length !== options.format.length) return false;
var formatDelimiter = options.delimiters.find(function (delimiter) {
return options.format.indexOf(delimiter) !== -1;
});
var dateDelimiter = options.strictMode ? formatDelimiter : options.delimiters.find(function (delimiter) {
return input.indexOf(delimiter) !== -1;
});
var dateAndFormat = zip(input.split(dateDelimiter), options.format.toLowerCase().split(formatDelimiter));
var dateObj = {};
var _iterator = _createForOfIteratorHelper(dateAndFormat),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray(_step.value, 2),
dateWord = _step$value[0],
formatWord = _step$value[1];
if (!dateWord || !formatWord || dateWord.length !== formatWord.length) {
return false;
}
dateObj[formatWord.charAt(0)] = dateWord;
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var fullYear = dateObj.y;
// Check if the year starts with a hyphen
if (fullYear.startsWith('-')) {
return false; // Hyphen before year is not allowed
}
if (dateObj.y.length === 2) {
var parsedYear = parseInt(dateObj.y, 10);
if (isNaN(parsedYear)) {
return false;
}
var currentYearLastTwoDigits = new Date().getFullYear() % 100;
if (parsedYear < currentYearLastTwoDigits) {
fullYear = "20".concat(dateObj.y);
} else {
fullYear = "19".concat(dateObj.y);
}
}
var month = dateObj.m;
if (dateObj.m.length === 1) {
month = "0".concat(dateObj.m);
}
var day = dateObj.d;
if (dateObj.d.length === 1) {
day = "0".concat(dateObj.d);
}
return new Date("".concat(fullYear, "-").concat(month, "-").concat(day, "T00:00:00.000Z")).getUTCDate() === +dateObj.d;
}
if (!options.strictMode) {
return Object.prototype.toString.call(input) === '[object Date]' && isFinite(input);
}
return false;
}
var default_time_options = {
hourFormat: 'hour24',
mode: 'default'
};
var formats = {
hour24: {
"default": /^([01]?[0-9]|2[0-3]):([0-5][0-9])$/,
withSeconds: /^([01]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/
},
hour12: {
"default": /^(0?[1-9]|1[0-2]):([0-5][0-9]) (A|P)M$/,
withSeconds: /^(0?[1-9]|1[0-2]):([0-5][0-9]):([0-5][0-9]) (A|P)M$/
}
};
function isTime(input, options) {
options = merge(options, default_time_options);
if (typeof input !== 'string') return false;
return formats[options.hourFormat][options.mode].test(input);
}
var defaultOptions = {
loose: false
};
var strictBooleans = ['true', 'false', '1', '0'];
var looseBooleans = [].concat(strictBooleans, ['yes', 'no']);
function isBoolean(str) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultOptions;
assertString(str);
if (options.loose) {
return looseBooleans.includes(str.toLowerCase());
}
return strictBooleans.includes(str);
}
/*
= 3ALPHA ; selected ISO 639 codes
*2("-" 3ALPHA) ; permanently reserved
*/
var extlang = '([A-Za-z]{3}(-[A-Za-z]{3}){0,2})';
/*
= 2*3ALPHA ; shortest ISO 639 code
["-" extlang] ; sometimes followed by
; extended language subtags
/ 4ALPHA ; or reserved for future use
/ 5*8ALPHA ; or registered language subtag
*/
var language = "(([a-zA-Z]{2,3}(-".concat(extlang, ")?)|([a-zA-Z]{5,8}))");
/*
= 4ALPHA ; ISO 15924 code
*/
var script = '([A-Za-z]{4})';
/*
= 2ALPHA ; ISO 3166-1 code
/ 3DIGIT ; UN M.49 code
*/
var region = '([A-Za-z]{2}|\\d{3})';
/*
= 5*8alphanum ; registered variants
/ (DIGIT 3alphanum)
*/
var variant = '([A-Za-z0-9]{5,8}|(\\d[A-Z-a-z0-9]{3}))';
/*
= DIGIT ; 0 - 9
/ %x41-57 ; A - W
/ %x59-5A ; Y - Z
/ %x61-77 ; a - w
/ %x79-7A ; y - z
*/
var singleton = '(\\d|[A-W]|[Y-Z]|[a-w]|[y-z])';
/*
= singleton 1*("-" (2*8alphanum))
; Single alphanumerics
; "x" reserved for private use
*/
var extension = "(".concat(singleton, "(-[A-Za-z0-9]{2,8})+)");
/*
= "x" 1*("-" (1*8alphanum))
*/
var privateuse = '(x(-[A-Za-z0-9]{1,8})+)';
// irregular tags do not match the 'langtag' production and would not
// otherwise be considered 'well-formed'. These tags are all valid, but
// most are deprecated in favor of more modern subtags or subtag combination
var irregular = '((en-GB-oed)|(i-ami)|(i-bnn)|(i-default)|(i-enochian)|' + '(i-hak)|(i-klingon)|(i-lux)|(i-mingo)|(i-navajo)|(i-pwn)|(i-tao)|' + '(i-tay)|(i-tsu)|(sgn-BE-FR)|(sgn-BE-NL)|(sgn-CH-DE))';
// regular tags match the 'langtag' production, but their subtags are not
// extended language or variant subtags: their meaning is defined by
// their registration and all of these are deprecated in favor of a more
// modern subtag or sequence of subtags
var regular = '((art-lojban)|(cel-gaulish)|(no-bok)|(no-nyn)|(zh-guoyu)|' + '(zh-hakka)|(zh-min)|(zh-min-nan)|(zh-xiang))';
/*
= irregular ; non-redundant tags registered
/ regular ; during the RFC 3066 era
*/
var grandfathered = "(".concat(irregular, "|").concat(regular, ")");
/*
RFC 5646 defines delimitation of subtags via a hyphen:
"Subtag" refers to a specific section of a tag, delimited by a
hyphen, such as the subtags 'zh', 'Hant', and 'CN' in the tag "zh-
Hant-CN". Examples of subtags in this document are enclosed in
single quotes ('Hant')
However, we need to add "_" to maintain the existing behaviour.
*/
var delimiter = '(-|_)';
/*
= language
["-" script]
["-" region]
*("-" variant)
*("-" extension)
["-" privateuse]
*/
var langtag = "".concat(language, "(").concat(delimiter).concat(script, ")?(").concat(delimiter).concat(region, ")?(").concat(delimiter).concat(variant, ")*(").concat(delimiter).concat(extension, ")*(").concat(delimiter).concat(privateuse, ")?");
/*
Regex implementation based on BCP RFC 5646
Tags for Identifying Languages
https://www.rfc-editor.org/rfc/rfc5646.html
*/
var languageTagRegex = new RegExp("(^".concat(privateuse, "$)|(^").concat(grandfathered, "$)|(^").concat(langtag, "$)"));
function isLocale(str) {
assertString(str);
return languageTagRegex.test(str);
}
// http://www.brainjar.com/js/validation/
// https://www.aba.com/news-research/research-analysis/routing-number-policy-procedures
// series reserved for future use are excluded
var isRoutingReg = /^(?!(1[3-9])|(20)|(3[3-9])|(4[0-9])|(5[0-9])|(60)|(7[3-9])|(8[1-9])|(9[0-2])|(9[3-9]))[0-9]{9}$/;
function isAbaRouting(str) {
assertString(str);
if (!isRoutingReg.test(str)) return false;
var checkSumVal = 0;
for (var i = 0; i < str.length; i++) {
if (i % 3 === 0) checkSumVal += str[i] * 3;else if (i % 3 === 1) checkSumVal += str[i] * 7;else checkSumVal += str[i] * 1;
}
return checkSumVal % 10 === 0;
}
function isAlpha(_str) {
var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
assertString(_str);
var str = _str;
var ignore = options.ignore;
if (ignore) {
if (ignore instanceof RegExp) {
str = str.replace(ignore, '');
} else if (typeof ignore === 'string') {
str = str.replace(new RegExp("[".concat(ignore.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&'), "]"), 'g'), ''); // escape regex for ignore
} else {
throw new Error('ignore should be instance of a String or RegExp');
}
}
if (locale in alpha) {
return alpha[locale].test(str);
}
throw new Error("Invalid locale '".concat(locale, "'"));
}
var locales$1 = Object.keys(alpha);
function isAlphanumeric(_str) {
var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
assertString(_str);
var str = _str;
var ignore = options.ignore;
if (ignore) {
if (ignore instanceof RegExp) {
str = str.replace(ignore, '');
} else if (typeof ignore === 'string') {
str = str.replace(new RegExp("[".concat(ignore.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&'), "]"), 'g'), ''); // escape regex for ignore
} else {
throw new Error('ignore should be instance of a String or RegExp');
}
}
if (locale in alphanumeric) {
return alphanumeric[locale].test(str);
}
throw new Error("Invalid locale '".concat(locale, "'"));
}
var locales$2 = Object.keys(alphanumeric);
var numericNoSymbols = /^[0-9]+$/;
function isNumeric(str, options) {
assertString(str);
if (options && options.no_symbols) {
return numericNoSymbols.test(str);
}
return new RegExp("^[+-]?([0-9]*[".concat((options || {}).locale ? decimal[options.locale] : '.', "])?[0-9]+$")).test(str);
}
/**
* Reference:
* https://en.wikipedia.org/ -- Wikipedia
* https://docs.microsoft.com/en-us/microsoft-365/compliance/eu-passport-number -- EU Passport Number
* https://countrycode.org/ -- Country Codes
*/
var passportRegexByCountryCode = {
AM: /^[A-Z]{2}\d{7}$/,
// ARMENIA
AR: /^[A-Z]{3}\d{6}$/,
// ARGENTINA
AT: /^[A-Z]\d{7}$/,
// AUSTRIA
AU: /^[A-Z]\d{7}$/,
// AUSTRALIA
AZ: /^[A-Z]{1}\d{8}$/,
// AZERBAIJAN
BE: /^[A-Z]{2}\d{6}$/,
// BELGIUM
BG: /^\d{9}$/,
// BULGARIA
BR: /^[A-Z]{2}\d{6}$/,
// BRAZIL
BY: /^[A-Z]{2}\d{7}$/,
// BELARUS
CA: /^[A-Z]{2}\d{6}$/,
// CANADA
CH: /^[A-Z]\d{7}$/,
// SWITZERLAND
CN: /^G\d{8}$|^E(?![IO])[A-Z0-9]\d{7}$/,
// CHINA [G=Ordinary, E=Electronic] followed by 8-digits, or E followed by any UPPERCASE letter (except I and O) followed by 7 digits
CY: /^[A-Z](\d{6}|\d{8})$/,
// CYPRUS
CZ: /^\d{8}$/,
// CZECH REPUBLIC
DE: /^[CFGHJKLMNPRTVWXYZ0-9]{9}$/,
// GERMANY
DK: /^\d{9}$/,
// DENMARK
DZ: /^\d{9}$/,
// ALGERIA
EE: /^([A-Z]\d{7}|[A-Z]{2}\d{7})$/,
// ESTONIA (K followed by 7-digits), e-passports have 2 UPPERCASE followed by 7 digits
ES: /^[A-Z0-9]{2}([A-Z0-9]?)\d{6}$/,
// SPAIN
FI: /^[A-Z]{2}\d{7}$/,
// FINLAND
FR: /^\d{2}[A-Z]{2}\d{5}$/,
// FRANCE
GB: /^\d{9}$/,
// UNITED KINGDOM
GR: /^[A-Z]{2}\d{7}$/,
// GREECE
HR: /^\d{9}$/,
// CROATIA
HU: /^[A-Z]{2}(\d{6}|\d{7})$/,
// HUNGARY
IE: /^[A-Z0-9]{2}\d{7}$/,
// IRELAND
IN: /^[A-Z]{1}-?\d{7}$/,
// INDIA
ID: /^[A-C]\d{7}$/,
// INDONESIA
IR: /^[A-Z]\d{8}$/,
// IRAN
IS: /^(A)\d{7}$/,
// ICELAND
IT: /^[A-Z0-9]{2}\d{7}$/,
// ITALY
JM: /^[Aa]\d{7}$/,
// JAMAICA
JP: /^[A-Z]{2}\d{7}$/,
// JAPAN
KR: /^[MS]\d{8}$/,
// SOUTH KOREA, REPUBLIC OF KOREA, [S=PS Passports, M=PM Passports]
KZ: /^[a-zA-Z]\d{7}$/,
// KAZAKHSTAN
LI: /^[a-zA-Z]\d{5}$/,
// LIECHTENSTEIN
LT: /^[A-Z0-9]{8}$/,
// LITHUANIA
LU: /^[A-Z0-9]{8}$/,
// LUXEMBURG
LV: /^[A-Z0-9]{2}\d{7}$/,
// LATVIA
LY: /^[A-Z0-9]{8}$/,
// LIBYA
MT: /^\d{7}$/,
// MALTA
MZ: /^([A-Z]{2}\d{7})|(\d{2}[A-Z]{2}\d{5})$/,
// MOZAMBIQUE
MY: /^[AHK]\d{8}$/,
// MALAYSIA
MX: /^\d{10,11}$/,
// MEXICO
NL: /^[A-Z]{2}[A-Z0-9]{6}\d$/,
// NETHERLANDS
NZ: /^([Ll]([Aa]|[Dd]|[Ff]|[Hh])|[Ee]([Aa]|[Pp])|[Nn])\d{6}$/,
// NEW ZEALAND
PH: /^([A-Z](\d{6}|\d{7}[A-Z]))|([A-Z]{2}(\d{6}|\d{7}))$/,
// PHILIPPINES
PK: /^[A-Z]{2}\d{7}$/,
// PAKISTAN
PL: /^[A-Z]{2}\d{7}$/,
// POLAND
PT: /^[A-Z]\d{6}$/,
// PORTUGAL
RO: /^\d{8,9}$/,
// ROMANIA
RU: /^\d{9}$/,
// RUSSIAN FEDERATION
SE: /^\d{8}$/,
// SWEDEN
SL: /^(P)[A-Z]\d{7}$/,
// SLOVENIA
SK: /^[0-9A-Z]\d{7}$/,
// SLOVAKIA
TH: /^[A-Z]{1,2}\d{6,7}$/,
// THAILAND
TR: /^[A-Z]\d{8}$/,
// TURKEY
UA: /^[A-Z]{2}\d{6}$/,
// UKRAINE
US: /^\d{9}$/,
// UNITED STATES
ZA: /^[TAMD]\d{8}$/ // SOUTH AFRICA
};
var locales$3 = Object.keys(passportRegexByCountryCode);
/**
* Check if str is a valid passport number
* relative to provided ISO Country Code.
*
* @param {string} str
* @param {string} countryCode
* @return {boolean}
*/
function isPassportNumber(str, countryCode) {
assertString(str);
/** Remove All Whitespaces, Convert to UPPERCASE */
var normalizedStr = str.replace(/\s/g, '').toUpperCase();
return countryCode.toUpperCase() in passportRegexByCountryCode && passportRegexByCountryCode[countryCode].test(normalizedStr);
}
var _int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/;
var intLeadingZeroes = /^[-+]?[0-9]+$/;
function isInt(str, options) {
assertString(str);
options = options || {};
// Get the regex to use for testing, based on whether
// leading zeroes are allowed or not.
var regex = options.allow_leading_zeroes === false ? _int : intLeadingZeroes;
// Check min/max/lt/gt
var minCheckPassed = !options.hasOwnProperty('min') || isNullOrUndefined(options.min) || str >= options.min;
var maxCheckPassed = !options.hasOwnProperty('max') || isNullOrUndefined(options.max) || str <= options.max;
var ltCheckPassed = !options.hasOwnProperty('lt') || isNullOrUndefined(options.lt) || str < options.lt;
var gtCheckPassed = !options.hasOwnProperty('gt') || isNullOrUndefined(options.gt) || str > options.gt;
return regex.test(str) && minCheckPassed && maxCheckPassed && ltCheckPassed && gtCheckPassed;
}
function isPort(str) {
return isInt(str, {
allow_leading_zeroes: false,
min: 0,
max: 65535
});
}
function isLowercase(str) {
assertString(str);
return str === str.toLowerCase();
}
function isUppercase(str) {
assertString(str);
return str === str.toUpperCase();
}
var imeiRegexWithoutHyphens = /^[0-9]{15}$/;
var imeiRegexWithHyphens = /^\d{2}-\d{6}-\d{6}-\d{1}$/;
function isIMEI(str, options) {
assertString(str);
options = options || {};
// default regex for checking imei is the one without hyphens
var imeiRegex = imeiRegexWithoutHyphens;
if (options.allow_hyphens) {
imeiRegex = imeiRegexWithHyphens;
}
if (!imeiRegex.test(str)) {
return false;
}
str = str.replace(/-/g, '');
var sum = 0,
mul = 2,
l = 14;
for (var i = 0; i < l; i++) {
var digit = str.substring(l - i - 1, l - i);