@lakutata/core
Version:
Lakutata Framework Core
708 lines (674 loc) • 26.5 kB
text/typescript
import {
BaseSchema,
ObjectSchema,
BooleanSchema,
NumberSchema,
StringSchema,
DateSchema,
string,
boolean,
number,
date,
mixed,
object,
array,
ref,
lazy,
addMethod
} from 'yup'
import {AnySchema} from 'yup/lib/schema'
import {AssertsShape, ObjectShape, OptionalObjectSchema, TypeOfShape} from 'yup/lib/object'
import {AnyObject, Maybe, Optionals} from 'yup/lib/types'
import Lazy, {LazyBuilder} from 'yup/lib/Lazy'
import {TypeOf} from 'yup/lib/util/types'
import {OptionalArraySchema} from 'yup/lib/array'
import Reference, {ReferenceOptions} from 'yup/lib/Reference'
import mapValues from 'lodash/mapValues'
import {ValidationException} from '../exceptions/ValidationException'
import isSsh from 'is-ssh'
import {MixedSchema} from 'yup/lib/mixed'
import {BaseObject} from './BaseObject'
import {validDataUrl} from '../utils/ValidDataUrl'
declare module 'yup' {
interface StringSchema {
ipv4(): StringSchema
ipv6(): StringSchema
ip(): StringSchema
ssh(): StringSchema
dataUrl(): StringSchema
url(option?: { acceptParams?: boolean; protocol?: string[] | string; blackHostnameList?: string[]; whiteHostnameList?: string[] }): StringSchema
phone(countryCode?: string, strict?: boolean): StringSchema
}
interface ObjectSchema<TShape extends ObjectShape, TContext extends AnyObject = AnyObject, TIn extends Maybe<TypeOfShape<TShape>> = TypeOfShape<TShape>, TOut extends Maybe<AssertsShape<TShape>> = AssertsShape<TShape> | Optionals<TIn>> extends BaseSchema<TIn, TContext, TOut> {
structure(valueSchema: AnySchema): OptionalObjectSchema<TShape, Record<string, any>, TypeOfShape<TShape>>
}
}
const IPV4_METHOD = 'ipv4'
const IPV6_METHOD = 'ipv6'
const IP_ALL_METHOD = 'ip'
const SSH_METHOD = 'ssh'
const URL_METHOD = 'url'
const DATA_URL_METHOD = 'dataUrl'
const STRUCTURE_METHOD = 'structure'
declare type ContextOf<T> = T extends AnySchema<any, infer C> ? C : never
export class ValidatorClass extends BaseObject {
/**
* 国家代码
* @type {{'Papua New Guinea': string, Cambodia: string, Kazakhstan: string, Paraguay: string, Syria: string, Bahamas: string, 'Solomon Islands': string, Montserrat: string, Mali: string, 'Marshall Islands': string, Panama: string, Laos: string, Vatican: string, Argentina: string, 'Falkland Islands': string, Seychelles: string, Belize: string, Zambia: string, Bahrain: string, 'Guinea-Bissau': string, 'Saint Barthelemy': string, Namibia: string, Comoros: string, 'Faroe Islands': string, Finland: string, 'Netherlands Antilles': string, Georgia: string, 'Saint Kitts and Nevis': string, Yemen: string, Eritrea: string, 'Puerto Rico': string, Aruba: string, Madagascar: string, 'Ivory Coast': string, Libya: string, 'Svalbard and Jan Mayen': string, 'Saint Martin': string, Sweden: string, Malawi: string, Andorra: string, Liechtenstein: string, Poland: string, Bulgaria: string, Jordan: string, Tunisia: string, Tuvalu: string, 'United Arab Emirates': string, Kenya: string, 'French Polynesia': string, Brunei: string, Djibouti: string, Lebanon: string, Azerbaijan: string, Cuba: string, 'Czech Republic': string, Mauritania: string, 'Saint Lucia': string, Guernsey: string, Mayotte: string, Israel: string, 'San Marino': string, Australia: string, Tajikistan: string, Myanmar: string, Cameroon: string, Gibraltar: string, Cyprus: string, 'Northern Mariana Islands': string, Malaysia: string, Iceland: string, Oman: string, Armenia: string, Gabon: string, Luxembourg: string, Brazil: string, 'Turks and Caicos Islands': string, Algeria: string, Jersey: string, Slovenia: string, 'Republic of the Congo': string, 'Antigua and Barbuda': string, Colombia: string, Ecuador: string, Moldova: string, Vanuatu: string, 'Cocos Islands': string, Honduras: string, Italy: string, Antarctica: string, Nauru: string, Haiti: string, Afghanistan: string, Burundi: string, Singapore: string, 'American Samoa': string, 'Christmas Island': string, Russia: string, Netherlands: string, China: string, 'Sint Maarten': string, 'Saint Pierre and Miquelon': string, Kyrgyzstan: string, Reunion: string, Bhutan: string, Romania: string, Togo: string, Philippines: string, Uzbekistan: string, Pitcairn: string, 'British Virgin Islands': string, Zimbabwe: string, 'British Indian Ocean Territory': string, Montenegro: string, Dominica: string, Indonesia: string, Benin: string, Angola: string, 'East Timor': string, Sudan: string, Portugal: string, 'New Caledonia': string, Grenada: string, 'North Korea': string, 'Cayman Islands': string, Greece: string, Latvia: string, Mongolia: string, Iran: string, Morocco: string, Guatemala: string, Guyana: string, Iraq: string, Chile: string, Nepal: string, 'Isle of Man': string, Tanzania: string, Ukraine: string, Ghana: string, Anguilla: string, India: string, Canada: string, Maldives: string, Turkey: string, Belgium: string, Taiwan: string, 'South Africa': string, 'Trinidad and Tobago': string, Bermuda: string, 'Central African Republic': string, 'Democratic Republic of the Congo': string, Jamaica: string, Peru: string, Turkmenistan: string, Germany: string, Fiji: string, Tokelau: string, 'Hong Kong': string, Guinea: string, 'United States': string, Chad: string, Somalia: string, 'Sao Tome and Principe': string, Thailand: string, 'Equatorial Guinea': string, Kiribati: string, 'Costa Rica': string, Vietnam: string, Kuwait: string, Nigeria: string, Croatia: string, 'Cook Islands': string, 'Sri Lanka': string, Uruguay: string, 'United Kingdom': string, Switzerland: string, Samoa: string, Palestine: string, Spain: string, Liberia: string, Venezuela: string, 'Burkina Faso': string, Swaziland: string, Palau: string, Estonia: string, 'Wallis and Futuna': string, Niue: string, Austria: string, 'South Korea': string, Mozambique: string, 'El Salvador': string, Monaco: string, Guam: string, Lesotho: string, Tonga: string, 'Western Sahara': string, Hungary: string, 'South Sudan': string, Japan: string, Belarus: string, Curacao: string, Mauritius: string, Albania: string, 'New Zealand': string, Senegal: string, Macedonia: string, Ethiopia: string, Egypt: string, Macau: string, 'Sierra Leone': string, Bolivia: string, Malta: string, 'Saudi Arabia': string, 'Cape Verde': string, Pakistan: string, Kosovo: string, Gambia: string, Ireland: string, Qatar: string, 'U.S. Virgin Islands': string, Slovakia: string, France: string, Lithuania: string, Serbia: string, 'Bosnia and Herzegovina': string, Niger: string, Rwanda: string, Bangladesh: string, Barbados: string, Nicaragua: string, Norway: string, Botswana: string, 'Saint Vincent and the Grenadines': string, Denmark: string, 'Dominican Republic': string, Mexico: string, Uganda: string, Micronesia: string, Suriname: string, Greenland: string, 'Saint Helena': string}}
*/
public readonly COUNTRY_CODE = {
'Afghanistan': 'AF',
'Albania': 'AL',
'Algeria': 'DZ',
'American Samoa': 'AS',
'Andorra': 'AD',
'Angola': 'AO',
'Anguilla': 'AI',
'Antarctica': 'AQ',
'Antigua and Barbuda': 'AG',
'Argentina': 'AR',
'Armenia': 'AM',
'Aruba': 'AW',
'Australia': 'AU',
'Austria': 'AT',
'Azerbaijan': 'AZ',
'Bahamas': 'BS',
'Bahrain': 'BH',
'Bangladesh': 'BD',
'Barbados': 'BB',
'Belarus': 'BY',
'Belgium': 'BE',
'Belize': 'BZ',
'Benin': 'BJ',
'Bermuda': 'BM',
'Bhutan': 'BT',
'Bolivia': 'BO',
'Bosnia and Herzegovina': 'BA',
'Botswana': 'BW',
'Brazil': 'BR',
'British Indian Ocean Territory': 'IO',
'British Virgin Islands': 'VG',
'Brunei': 'BN',
'Bulgaria': 'BG',
'Burkina Faso': 'BF',
'Burundi': 'BI',
'Cambodia': 'KH',
'Cameroon': 'CM',
'Canada': 'CA',
'Cape Verde': 'CV',
'Cayman Islands': 'KY',
'Central African Republic': 'CF',
'Chad': 'TD',
'Chile': 'CL',
'China': 'CN',
'Christmas Island': 'CX',
'Cocos Islands': 'CC',
'Colombia': 'CO',
'Comoros': 'KM',
'Cook Islands': 'CK',
'Costa Rica': 'CR',
'Croatia': 'HR',
'Cuba': 'CU',
'Curacao': 'CW',
'Cyprus': 'CY',
'Czech Republic': 'CZ',
'Democratic Republic of the Congo': 'CD',
'Denmark': 'DK',
'Djibouti': 'DJ',
'Dominica': 'DM',
'Dominican Republic': 'DO',
'East Timor': 'TL',
'Ecuador': 'EC',
'Egypt': 'EG',
'El Salvador': 'SV',
'Equatorial Guinea': 'GQ',
'Eritrea': 'ER',
'Estonia': 'EE',
'Ethiopia': 'ET',
'Falkland Islands': 'FK',
'Faroe Islands': 'FO',
'Fiji': 'FJ',
'Finland': 'FI',
'France': 'FR',
'French Polynesia': 'PF',
'Gabon': 'GA',
'Gambia': 'GM',
'Georgia': 'GE',
'Germany': 'DE',
'Ghana': 'GH',
'Gibraltar': 'GI',
'Greece': 'GR',
'Greenland': 'GL',
'Grenada': 'GD',
'Guam': 'GU',
'Guatemala': 'GT',
'Guernsey': 'GG',
'Guinea': 'GN',
'Guinea-Bissau': 'GW',
'Guyana': 'GY',
'Haiti': 'HT',
'Honduras': 'HN',
'Hong Kong': 'HK',
'Hungary': 'HU',
'Iceland': 'IS',
'India': 'IN',
'Indonesia': 'ID',
'Iran': 'IR',
'Iraq': 'IQ',
'Ireland': 'IE',
'Isle of Man': 'IM',
'Israel': 'IL',
'Italy': 'IT',
'Ivory Coast': 'CI',
'Jamaica': 'JM',
'Japan': 'JP',
'Jersey': 'JE',
'Jordan': 'JO',
'Kazakhstan': 'KZ',
'Kenya': 'KE',
'Kiribati': 'KI',
'Kosovo': 'XK',
'Kuwait': 'KW',
'Kyrgyzstan': 'KG',
'Laos': 'LA',
'Latvia': 'LV',
'Lebanon': 'LB',
'Lesotho': 'LS',
'Liberia': 'LR',
'Libya': 'LY',
'Liechtenstein': 'LI',
'Lithuania': 'LT',
'Luxembourg': 'LU',
'Macau': 'MO',
'Macedonia': 'MK',
'Madagascar': 'MG',
'Malawi': 'MW',
'Malaysia': 'MY',
'Maldives': 'MV',
'Mali': 'ML',
'Malta': 'MT',
'Marshall Islands': 'MH',
'Mauritania': 'MR',
'Mauritius': 'MU',
'Mayotte': 'YT',
'Mexico': 'MX',
'Micronesia': 'FM',
'Moldova': 'MD',
'Monaco': 'MC',
'Mongolia': 'MN',
'Montenegro': 'ME',
'Montserrat': 'MS',
'Morocco': 'MA',
'Mozambique': 'MZ',
'Myanmar': 'MM',
'Namibia': 'NA',
'Nauru': 'NR',
'Nepal': 'NP',
'Netherlands': 'NL',
'Netherlands Antilles': 'AN',
'New Caledonia': 'NC',
'New Zealand': 'NZ',
'Nicaragua': 'NI',
'Niger': 'NE',
'Nigeria': 'NG',
'Niue': 'NU',
'North Korea': 'KP',
'Northern Mariana Islands': 'MP',
'Norway': 'NO',
'Oman': 'OM',
'Pakistan': 'PK',
'Palau': 'PW',
'Palestine': 'PS',
'Panama': 'PA',
'Papua New Guinea': 'PG',
'Paraguay': 'PY',
'Peru': 'PE',
'Philippines': 'PH',
'Pitcairn': 'PN',
'Poland': 'PL',
'Portugal': 'PT',
'Puerto Rico': 'PR',
'Qatar': 'QA',
'Republic of the Congo': 'CG',
'Reunion': 'RE',
'Romania': 'RO',
'Russia': 'RU',
'Rwanda': 'RW',
'Saint Barthelemy': 'BL',
'Saint Helena': 'SH',
'Saint Kitts and Nevis': 'KN',
'Saint Lucia': 'LC',
'Saint Martin': 'MF',
'Saint Pierre and Miquelon': 'PM',
'Saint Vincent and the Grenadines': 'VC',
'Samoa': 'WS',
'San Marino': 'SM',
'Sao Tome and Principe': 'ST',
'Saudi Arabia': 'SA',
'Senegal': 'SN',
'Serbia': 'RS',
'Seychelles': 'SC',
'Sierra Leone': 'SL',
'Singapore': 'SG',
'Sint Maarten': 'SX',
'Slovakia': 'SK',
'Slovenia': 'SI',
'Solomon Islands': 'SB',
'Somalia': 'SO',
'South Africa': 'ZA',
'South Korea': 'KR',
'South Sudan': 'SS',
'Spain': 'ES',
'Sri Lanka': 'LK',
'Sudan': 'SD',
'Suriname': 'SR',
'Svalbard and Jan Mayen': 'SJ',
'Swaziland': 'SZ',
'Sweden': 'SE',
'Switzerland': 'CH',
'Syria': 'SY',
'Taiwan': 'TW',
'Tajikistan': 'TJ',
'Tanzania': 'TZ',
'Thailand': 'TH',
'Togo': 'TG',
'Tokelau': 'TK',
'Tonga': 'TO',
'Trinidad and Tobago': 'TT',
'Tunisia': 'TN',
'Turkey': 'TR',
'Turkmenistan': 'TM',
'Turks and Caicos Islands': 'TC',
'Tuvalu': 'TV',
'U.S. Virgin Islands': 'VI',
'Uganda': 'UG',
'Ukraine': 'UA',
'United Arab Emirates': 'AE',
'United Kingdom': 'GB',
'United States': 'US',
'Uruguay': 'UY',
'Uzbekistan': 'UZ',
'Vanuatu': 'VU',
'Vatican': 'VA',
'Venezuela': 'VE',
'Vietnam': 'VN',
'Wallis and Futuna': 'WF',
'Western Sahara': 'EH',
'Yemen': 'YE',
'Zambia': 'ZM',
'Zimbabwe': 'ZW'
}
/**
* 字符串验证器
* @returns {StringSchema<string | undefined, Record<string, any>, string | undefined>}
* @constructor
*/
public get String(): StringSchema<string | undefined, Record<string, any>, string | undefined> {
return string()
}
/**
* 邮箱验证器
* @returns {StringSchema<string | undefined, Record<string, any>, string | undefined>}
* @constructor
*/
public get Email(): StringSchema<string | undefined, Record<string, any>, string | undefined> {
return string().email()
}
/**
* SSH连接字符串验证器
* @returns {StringSchema<string | undefined, Record<string, any>, string | undefined>}
* @constructor
*/
public get SSH(): StringSchema<string | undefined, Record<string, any>, string | undefined> {
return string().ssh()
}
/**
* DataURL验证器
* @returns {StringSchema<string | undefined, Record<string, any>, string | undefined>}
* @constructor
*/
public get DataURL(): StringSchema<string | undefined, Record<string, any>, string | undefined> {
return string().dataUrl()
}
/**
* 布尔类型验证器
* @returns {BooleanSchema<boolean | undefined, Record<string, any>, boolean | undefined>}
* @constructor
*/
public get Bool(): BooleanSchema<boolean | undefined, Record<string, any>, boolean | undefined> {
return this.Boolean
}
/**
* 布尔类型验证器
* @returns {BooleanSchema<boolean | undefined, Record<string, any>, boolean | undefined>}
* @constructor
*/
public get Boolean(): BooleanSchema<boolean | undefined, Record<string, any>, boolean | undefined> {
return boolean()
}
/**
* 数字验证器
* @returns {NumberSchema<number | undefined, Record<string, any>, number | undefined>}
* @constructor
*/
public get Number(): NumberSchema<number | undefined, Record<string, any>, number | undefined> {
return number()
}
/**
* 整数验证器
* @returns {NumberSchema<number | undefined, Record<string, any>, number | undefined>}
* @constructor
*/
public get Integer(): NumberSchema<number | undefined, Record<string, any>, number | undefined> {
return this.Number.integer()
}
/**
* 日期验证器
* @returns {DateSchema<Date | undefined, Record<string, any>, Date | undefined>}
* @constructor
*/
public get Date(): DateSchema<Date | undefined, Record<string, any>, Date | undefined> {
return date()
}
/**
* Any类型验证器
* @returns {MixedSchema<any, Record<string, any>, any>}
* @constructor
*/
public get Any(): MixedSchema<any, Record<string, any>, any> {
return mixed() as MixedSchema<any, Record<string, any>, any>
}
/**
* URL验证器
* @param {{acceptParams?: boolean, protocol?: string[] | string, blackHostnameList?: string[], whiteHostnameList?: string[]}} option
* @returns {StringSchema<string | undefined, Record<string, any>, string | undefined>}
* @constructor
*/
public URL(option?: { acceptParams?: boolean; protocol?: string[] | string; blackHostnameList?: string[]; whiteHostnameList?: string[] }): StringSchema<string | undefined, Record<string, any>, string | undefined> {
return this.String.url(option)
}
/**
* 电话号码验证器
* @param {string} countryCode
* @param {boolean} strict
* @returns {StringSchema<string | undefined, Record<string, any>, string | undefined>}
* @constructor
*/
public Phone(countryCode?: string, strict?: boolean): StringSchema<string | undefined, Record<string, any>, string | undefined> {
return string().phone(countryCode?.toUpperCase(), strict)
}
/**
* IP地址验证器
* @param {"ipv4" | "ipv6" | "both"} mode
* @returns {StringSchema<string | undefined, Record<string, any>, string | undefined>}
* @constructor
*/
public IP(mode: 'ipv4' | 'ipv6' | 'both' = 'both'): StringSchema<string | undefined, Record<string, any>, string | undefined> {
switch (mode) {
case 'ipv4': {
return string().ipv4()
}
case 'ipv6': {
return string().ipv6()
}
case 'both': {
return string().ip()
}
default: {
return string().ip()
}
}
}
/**
* Object对象验证器
* @returns {OptionalObjectSchema<TShape, Record<string, any>, TypeOfShape<TShape>>}
* @constructor
*/
public Object<TShape extends ObjectShape>(spec?: TShape): OptionalObjectSchema<TShape, Record<string, any>, TypeOfShape<TShape>>
public Object<TShape extends ObjectShape>(structure?: AnySchema): OptionalObjectSchema<TShape, Record<string, any>, TypeOfShape<TShape>>
public Object<TShape extends ObjectShape>(spec?: TShape, structure?: AnySchema): OptionalObjectSchema<TShape, Record<string, any>, TypeOfShape<TShape>>
public Object(a?, b?) {
if (a !== undefined) {
if (arguments.length === 2) {
return object(a).structure(b)
} else {
if (a.__isYupSchema__) {
return object().structure(a)
} else {
return object(a)
}
}
} else {
return object(a)
}
}
/**
* 键值对验证器
* @param {T} valueType
* @returns {Lazy<any, ContextOf<T>>}
* @constructor
*/
public KeyValueStructure<T extends AnySchema>(valueType: T): Lazy<any, ContextOf<T>> {
return this.Lazy(obj =>
this.Object(mapValues(obj, () => {
return valueType.required()
})
).default({})
)
}
/**
* 数组验证器
* @param {T} type
* @returns {OptionalArraySchema<T, C, TypeOf<T>[] | undefined>}
* @constructor
*/
public Array<C extends AnyObject = AnyObject, T extends AnySchema | Lazy<any, any> = AnySchema>(type?: T): OptionalArraySchema<T, C, TypeOf<T>[] | undefined> {
return array(type)
}
/**
* 引用验证器
* @param {string} key
* @param {ReferenceOptions<TValue>} options
* @returns {Reference<TValue>}
* @constructor
*/
public Ref<TValue = unknown>(key: string, options?: ReferenceOptions<TValue>): Reference<TValue> {
return ref(key, options)
}
/**
* Lazy验证器
* @param {LazyBuilder<T>} builder
* @returns {Lazy<T, ContextOf<T>>}
* @constructor
*/
public Lazy<T extends AnySchema>(builder: LazyBuilder<T>): Lazy<T, ContextOf<T>> {
return lazy(builder)
}
constructor() {
super()
addMethod(string, IPV4_METHOD, function (this: StringSchema, message = 'Invalid IP address') {
return this.matches(/(^(\d{1,3}\.){3}(\d{1,3})$)/, {
message,
excludeEmptyString: true
}).test('ip', message, value => {
return value === undefined || value.trim() === ''
? true
: value.split('.').find(i => parseInt(i, 10) > 255) === undefined
})
})
addMethod(string, IPV6_METHOD, function (this: StringSchema, message = 'Invalid IP address') {
return this.matches(/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/, {
message,
excludeEmptyString: true
}).test('ip', message, value => {
return !(value === undefined || value.trim() === '')
})
})
addMethod(string, IP_ALL_METHOD, function (this: StringSchema, message = 'Invalid IP address') {
const combinedIpRegExp: RegExp = /((^(\d{1,3}\.){3}(\d{1,3})$)|([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/
const ipv4RegExp: RegExp = /(^(\d{1,3}\.){3}(\d{1,3})$)/
const ipv6RegExp: RegExp = /(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/
return this.matches(combinedIpRegExp, {
message,
excludeEmptyString: true
}).test('ip', message, value => {
if (ipv4RegExp.test(value ? value.toString() : '')) {
return value === undefined || value.trim() === ''
? true
: value.split('.').find(i => parseInt(i, 10) > 255) === undefined
} else if (ipv6RegExp.test(value ? value.toString() : '')) {
return !(value === undefined || value.trim() === '')
} else {
return false
}
})
})
addMethod(string, SSH_METHOD, function (this: StringSchema, message = 'Invalid SSH URL') {
return this.matches(/[\s\S]*/, {
message,
excludeEmptyString: true
}).test('url', message, value => {
if (!value) {
return false
}
return isSsh(value)
})
})
addMethod(string, DATA_URL_METHOD, function (this: StringSchema, message = 'Invalid Data URL') {
return this.matches(/[\s\S]*/, {
message,
excludeEmptyString: true
}).test('url', message, value => {
if (!value) {
return false
}
return validDataUrl(value)
})
})
addMethod(string, URL_METHOD, function (this: StringSchema, message = 'Invalid URL') {
return this.matches(/^((https|http|ftp|rtsp|mms|wss|ws):\/\/)(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z].[a-z]{2,6})(:[0-9]{1,4})?((\/?)|(\/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+\/?)$/, {
message,
excludeEmptyString: true
}).test('url', message, value => {
if (!value) {
return false
} else {
const urlOption: {
acceptParams: boolean
protocol: string[] | string
blackHostnameList?: string[]
whiteHostnameList?: string[]
} = Object.assign({
acceptParams: true,
protocol: ['http', 'https', 'ftp', 'rtsp', 'mms', 'wss', 'ws']
}, arguments[0] ? (typeof arguments[0] === 'object' ? arguments[0] : {}) : {})
const urlObject = new URL(value)
const blackHostnameList: RegExp[] = urlOption.blackHostnameList ? (() => {
const _blackHostnameList: RegExp[] = []
for (const blackHostname of urlOption.blackHostnameList) {
_blackHostnameList.push(new RegExp(blackHostname.trim().replace(/\*/g, '[\\s\\S]*')))
}
return _blackHostnameList
})() : []
const whiteHostnameList: RegExp[] = urlOption.whiteHostnameList ? (() => {
const _whiteHostnameList: RegExp[] = []
for (const whiteHostname of urlOption.whiteHostnameList) {
_whiteHostnameList.push(new RegExp(whiteHostname.trim().replace(/\*/g, '[\\s\\S]*')))
}
return _whiteHostnameList
})() : []
const protocols: string[] = Array.isArray(urlOption.protocol) ? (() => {
const _protocols: string[] = []
for (const protocol of urlOption.protocol) {
_protocols.push(protocol.toLowerCase())
}
return _protocols
})() : [urlOption.protocol.toLowerCase()]
const acceptParams: boolean = urlOption.acceptParams
if (!acceptParams && !!urlObject.search) return false
if (protocols.indexOf(urlObject.protocol.replace(':', '').trim().toLowerCase()) === -1) return false
if (blackHostnameList.length > 0 || whiteHostnameList.length > 0) {
const listMode: 'black' | 'white' = (() => {
if (whiteHostnameList.length > 0) {
return 'white'
} else {
return 'black'
}
})()
switch (listMode) {
case 'black': {
for (const blackRegExp of blackHostnameList) {
if (blackRegExp.test(urlObject.hostname)) return false
}
return true
}
case 'white': {
for (const whiteRegExp of whiteHostnameList) {
if (whiteRegExp.test(urlObject.hostname)) return true
}
return false
}
}
}
return true
}
})
})
addMethod(object, STRUCTURE_METHOD, function (this: ObjectSchema<AnyObject>) {
return this.test('structure', value => {
const schema: AnySchema = arguments[0]
lazy(obj =>
object(mapValues(obj, () => {
return schema.required()
})
).default({})
).validateSync(value, {strict: true})
return true
})
})
}
/**
* 异步验证
* @param {SchemaType} schema
* @param {DataType} data
* @returns {Promise<DataType>}
*/
public async validate<SchemaType extends AnySchema, DataType = any>(schema: SchemaType, data: DataType): Promise<DataType> {
try {
return await schema.validate(data, {strict: true})
} catch (e) {
throw this.generateException(ValidationException, (e as Error).message)
}
}
/**
* 同步验证
* @param {SchemaType} schema
* @param {DataType} data
* @returns {DataType}
*/
public validateSync<SchemaType extends AnySchema, DataType = any>(schema: SchemaType, data: DataType): DataType {
try {
return schema.validateSync(data, {strict: true})
} catch (e) {
throw this.generateException(ValidationException, (e as Error).message)
}
}
/**
* 异步验证数据是否正确
* @param {SchemaType} schema
* @param {DataType} data
* @returns {Promise<boolean>}
*/
public async isValid<SchemaType extends AnySchema, DataType = any>(schema: SchemaType, data: DataType): Promise<boolean> {
return await schema.isValid(data, {strict: true})
}
/**
* 同步验证数据是否正确
* @param {SchemaType} schema
* @param {DataType} data
* @returns {boolean}
*/
public isValidSync<SchemaType extends AnySchema, DataType = any>(schema: SchemaType, data: DataType): boolean {
return schema.isValidSync(data, {strict: true})
}
}