mallBackend/src/utils/validate.ts

51 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-12-02 11:33:44 +08:00
/* eslint-disable @typescript-eslint/no-explicit-any */
// 是否在浏览器
export const inBrowser = typeof window !== 'undefined'
// 数值或者字符串
export type Numeric = number | string
//是否定义
export const isDef = <T>(val: T): val is NonNullable<T> =>
val !== undefined && val !== null
// eslint-disable-next-line @typescript-eslint/ban-types
// 是否是函数
export const isFunction = (val: unknown) => typeof val === 'function'
// 是否是对象
export const isObject = (val: unknown): val is Record<any, any> =>
val !== null && typeof val === 'object'
// 是否是promise
export const isPromise = <T = any>(val: unknown): val is Promise<T> =>
isObject(val) && isFunction(val.then) && isFunction(val.catch)
// 是否是日期
export const isDate = (val: unknown): val is Date =>
Object.prototype.toString.call(val) === '[object Date]' &&
!Number.isNaN((val as Date).getTime())
// 是否是电话
export function isMobile(value: string): boolean {
value = value.replace(/[^-|\d]/g, '')
return (
/^((\+86)|(86))?(1)\d{10}$/.test(value) ||
/^0[0-9-]{10,13}$/.test(value)
)
}
// 能否转换成数值类型
export const isNumeric = (val: Numeric): val is string =>
typeof val === 'number' || /^\d+(\.\d+)?$/.test(val)
// 是不是 ios 环境
export const isIOS = inBrowser
? /ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase())
: false
export const isAndroid = inBrowser
? /android|linux/.test(navigator.userAgent.toLowerCase())
: false