前端常用的验证方法

本文介绍了JavaScript中一系列的验证函数,如邮箱、手机号、URL等格式验证,以及数据类型检测、用户代理分析、数组操作和URL参数提取等实用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1、邮箱验证

export const isEmail = (s) => {    return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}

2、手机号码验证

export const isMobile = (s) => {    return /^1[0-9]{10}$/.test(s)
}

3、电话号码验证

export const isPhone = (s) => {    return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s)
}

4、是否url地址

export const isURL = (s) => {    return /^http[s]?:\/\/.*/.test(s)
}

5、是否字符串

export const isString = (o) => {    return Object.prototype.toString.call(o).slice(8, -1) === 'String'}

6、是否数字


export const isNumber = (o) => {    return Object.prototype.toString.call(o).slice(8, -1) === 'Number'}

7、是否boolean

export const isBoolean = (o) => {    return Object.prototype.toString.call(o).slice(8, -1) === 'Boolean'}

8、是否函数

export const isFunction = (o) => {    return Object.prototype.toString.call(o).slice(8, -1) === 'Function'}

9、是否为null

export const isNull = (o) => {    return Object.prototype.toString.call(o).slice(8, -1) === 'Null'}

10、是否undefined


export const isUndefined = (o) => {    return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined'}

11、是否对象

export const isObj = (o) => {    return Object.prototype.toString.call(o).slice(8, -1) === 'Object'}

12、是否数组

export const isArray = (o) => {    return Object.prototype.toString.call(o).slice(8, -1) === 'Array'}

13、是否时间

export const isDate = (o) => {    return Object.prototype.toString.call(o).slice(8, -1) === 'Date'}

14、是否正则

export const isRegExp = (o) => {    return Object.prototype.toString.call(o).slice(8, -1) === 'RegExp'}

15、是否错误对象

export const isError = (o) => {    return Object.prototype.toString.call(o).slice(8, -1) === 'Error'}

17、是否Promise对象

export const isPromise = (o) => {    return Object.prototype.toString.call(o).slice(8, -1) === 'Promise'}

18、是否Set对象

export const isSet = (o) => {  
    return Object.prototype.toString.call(o).slice(8, -1) === 'Set'}
/**
* @param ua 获取userAgent类型
**/export const ua = navigator.userAgent.toLowerCase();

19、是否是微信浏览器

export const isWeiXin = () => {    return ua.match(/microMessenger/i) == 'micromessenger'}

20、是否是移动端

export const isDeviceMobile = () => { 
    return /android|webos|iphone|ipod|balckberry/i.test(ua)
}

21、是否是QQ浏览器

export const isQQBrowser = () => {    return !!ua.match(/mqqbrowser|qzone|qqbrowser|qbwebviewtype/i)
}

22、是否ios

export const isIos = () => {    var u = navigator.userAgent;    if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {  //安卓手机
        return false
    } else if (u.indexOf('iPhone') > -1) {//苹果手机
        return true
    } else if (u.indexOf('iPad') > -1) {//iPad
        return false
    } else if (u.indexOf('Windows Phone') > -1) {//winphone手机
        return false
    } else {        return false
    }
}

23、是否为PC端

export const isPC = () => {    var userAgentInfo = navigator.userAgent;    var Agents = ["Android", "iPhone","SymbianOS", "Windows Phone",        "iPad", "iPod"];    var flag = true;    for (var v = 0; v < Agents.length; v++) {        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;            break;
        }
    }    return flag;
}

24、去除html标签

export const removehtmltag = (str) => {    return str.replace(/<[^>]+>/g, '')
}

25、判断类型集合

export const checkStr = (str, type) => {    switch (type) {        case 'phone':   //手机号码
            return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);        case 'tel':     //座机
            return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);        case 'card':    //身份证
            return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);        case 'pwd':     //密码以字母开头,长度在6~18之间,只能包含字母、数字和下划线
            return /^[a-zA-Z]\w{5,17}$/.test(str)        case 'postal':  //邮政编码
            return /[1-9]\d{5}(?!\d)/.test(str);        case 'QQ':      //QQ号
            return /^[1-9][0-9]{4,9}$/.test(str);        case 'email':   //邮箱
            return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);        case 'money':   //金额(小数点2位)
            return /^\d*(?:\.\d{0,2})?$/.test(str);        case 'URL':     //网址
            return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)        case 'IP':      //IP
            return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);        case 'date':    //日期时间
            return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)        case 'number':  //数字
            return /^[0-9]$/.test(str);        case 'english': //英文
            return /^[a-zA-Z]+$/.test(str);        case 'chinese': //中文
            return /^[\\u4E00-\\u9FA5]+$/.test(str);        case 'lower':   //小写
            return /^[a-z]+$/.test(str);        case 'upper':   //大写
            return /^[A-Z]+$/.test(str);        case 'HTML':    //HTML标记
            return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);        default:            return true;
    }
}

26、获取url参数

export const getQueryString = (name) => {    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');    const search = window.location.search.split('?')[1] || '';    const r = search.match(reg) || [];    return r[2];
}

27、将阿拉伯数字翻译成中文的大写数字

export const numberToChinese = (num) => {    var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十");    var BB = new Array("", "十", "百", "仟", "萬", "億", "点", "");    var a = ("" + num).replace(/(^0*)/g, "").split("."),
        k = 0,
        re = "";    for (var i = a[0].length - 1; i >= 0; i--) {        switch (k) {            case 0:
                re = BB[7] + re;                break;            case 4:                if (!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$")
                    .test(a[0]))
                    re = BB[4] + re;                break;            case 8:
                re = BB[5] + re;
                BB[7] = BB[5];
                k = 0;                break;
        }        if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0)
            re = AA[0] + re;        if (a[0].charAt(i) != 0)
            re = AA[a[0].charAt(i)] + BB[k % 4] + re;
        k++;
    }    if (a.length > 1) // 加上小数部分(如果有小数部分)
    {
        re += BB[6];        for (var i = 0; i < a[1].length; i++)
            re += AA[a[1].charAt(i)];
    }    if (re == '一十')
        re = "十";    if (re.match(/^一/) && re.length == 3)
        re = re.replace("一", "");    return re;
}

28、数组中的最大值

export const max = (arr) => {    return Math.max.apply(null, arr);
}

29、数组中的最小值

export const min = (arr) => {    return Math.min.apply(null, arr);
}

30、数组中的求和

export const sum = (arr) => {    return arr.reduce((pre, cur) => {        return pre + cur
    })
}

31、数组中的平均值

export const average = (arr) => {    return this.sum(arr) / arr.length
}

32、函数节流器

export const debouncer = (fn, time, interval = 200) => {    if (time - (window.debounceTimestamp || 0) > interval) {
        fn && fn();        window.debounceTimestamp = time;
    }
}

33、删除其中一个元素

export const remove = (arr, ele) => {    var index = arr.indexOf(ele);    if (index > -1) {
        arr.splice(index, 1);
    }    return arr;
}

34、获取URL参数

export const getQueryString = (name) => {    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");    let r = url.substr(1).match(reg);    if (r != null) {        return decodeURI(r[2]);
    } else {        return "";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值