js常见的输入值校验和替换操作

    |     2020年3月20日   |   html/css/js, web前端技术   |     0 条评论   |    1294

表单里最常见的两类操作是校验和替换。下面这组函数覆盖数字、手机号、邮箱、身份证、URL、IP 以及密码复杂度。原文:https://github.com/Wscats/CV/issues/27。实现按原逻辑保留,并修正 functionpureNum 的函数名。

isNum 要求入参已是 number;isInt 正则带可选负号,实际校验的是非零整数而不是“正整数”。anysicIntLength 负责拼整数位数的正则量词。

一、数字与整数

isNum / anysicIntLength:数字与小数位

校验是否为一个数字,以及该数字小数点位数是否与参数floats一致 校验规则: 若参数floats有值,则校验该数字小数点后的位数。 若参数floats没有值,则仅仅校验是否为数字。

function isNum(value,floats=null){

    let regexp = new RegExp(`^[1-9][0-9]*.[0-9]{${floats}}$|^0.[0-9]{${floats}}$`);

    return typeof value === 'number' && floats?regexp.test(String(value)):true;

}

function anysicIntLength(minLength,maxLength){

    let result_str = '';

    if(minLength){

        switch(maxLength){

            case undefined:

                result_str = result_str.concat(`{${minLength-1}}`);

                break;

            case null:

                result_str = result_str.concat(`{${minLength-1},}`);

                break;

            default:

                result_str = result_str.concat(`{${minLength-1},${maxLength-1}}`);

        }

    }else{

        result_str = result_str.concat('*');

    }



    return result_str;

}

isInt:非零整数(可带符号)

校验是否为非零的正整数

function isInt(value,minLength=null,maxLength=undefined){

    if(!isNum(value)) return false;



    let regexp = new RegExp(`^-?[1-9][0-9]${anysicIntLength(minLength,maxLength)}$`);

    return regexp.test(value.toString());

}

isPInt:非零正整数

校验是否为非零的正整数

function isPInt(value,minLength=null,maxLength=undefined) {

    if(!isNum(value)) return false;



    let regexp = new RegExp(`^[1-9][0-9]${anysicIntLength(minLength,maxLength)}$`);

    return regexp.test(value.toString());

}

isNInt:非零负整数

校验是否为非零的负整数

function isNInt(value,minLength=null,maxLength=undefined){

    if(!isNum(value)) return false;

    let regexp = new RegExp(`^-[1-9][0-9]${anysicIntLength(minLength,maxLength)}$`);

    return regexp.test(value.toString());

}

checkIntRange:整数取值范围

校验整数是否在取值范围内 校验规则: minInt为在取值范围中最小的整数 maxInt为在取值范围中最大的整数

function checkIntRange(value,minInt,maxInt=9007199254740991){

    return Boolean(isInt(value) && (Boolean(minInt!=undefined && minInt!=null)?value>=minInt:true) && (value<=maxInt));

}

二、联系方式、证件与地址

isTel:大陆手机号

校验是否为中国大陆手机号

function isTel(value) {

    return /^1[3,4,5,6,7,8,9][0-9]{9}$/.test(value.toString());

}

isFax:传真 / 固话

校验是否为中国大陆传真或固定电话号码

function isFax(str) {

    return /^([0-9]{3,4})?[0-9]{7,8}$|^([0-9]{3,4}-)?[0-9]{7,8}$/.test(str);

}

isEmail:邮箱

校验是否为邮箱地址

function isEmail(str) {

    return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(str);

}

isQQ:QQ 号

校验是否为QQ号码 校验规则: 非0开头的5位-13位整数

function isQQ(value) {

    return /^[1-9][0-9]{4,12}$/.test(value.toString());

}

isURL:网址

校验是否为网址 校验规则: 以https://、http://、ftp://、rtsp://、mms://开头、或者没有这些开头 可以没有www开头(或其他二级域名),仅域名 网页地址中允许出现/%*?@&等其他允许的符号

function isURL(str) {

    return /^(https:\/\/|http:\/\/|ftp:\/\/|rtsp:\/\/|mms:\/\/)?[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test(str);

}

isIP:IPv4(不含端口)

校验是否为不含端口号的IP地址 校验规则: IP格式为xxx.xxx.xxx.xxx,每一项数字取值范围为0-255 除0以外其他数字不能以0开头,比如02

function isIP(str) {

    return /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$/.test(str);

}

isIPv6:IPv6 正常与压缩格式

校验是否为IPv6地址 校验规则: 支持IPv6正常格式 支持IPv6压缩格式

function isIPv6(str){

    return Boolean(str.match(/:/g)?str.match(/:/g).length<=7:false && /::/.test(str)?/^([\da-f]{1,4}(:|::)){1,6}[\da-f]{1,4}$/i.test(str):/^([\da-f]{1,4}:){7}[\da-f]{1,4}$/i.test(str));

}

isIDCard:二代身份证

校验是否为中国大陆第二代居民身份证 校验规则: 共18位,最后一位可为X(大小写均可) 不能以0开头 出生年月日会进行校验:年份只能为18/19/2*开头,月份只能为01-12,日只能为01-31

function isIDCard(str){

    return /^[1-9][0-9]{5}(18|19|(2[0-9]))[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{3}[0-9Xx]$/.test(str);

}

isPostCode:邮政编码

校验是否为中国大陆邮政编码 参数value为数字或字符串 校验规则: 共6位,且不能以0开头

function isPostCode(value){

    return /^[1-9][0-9]{5}$/.test(value.toString());

}

三、字符串构成与密码强度

same:值与类型都相同

校验两个参数是否完全相同,包括类型 校验规则: 值相同,数据类型也相同

function same(firstValue,secondValue){

    return firstValue===secondValue;

}

lengthRange:字符长度范围

校验字符的长度是否在规定的范围内 校验规则: minInt为在取值范围中最小的长度 maxInt为在取值范围中最大的长度

function lengthRange(str,minLength,maxLength=9007199254740991) {

    return Boolean(str.length >= minLength && str.length <= maxLength);

}

letterBegin:字母开头

校验字符是否以字母开头 校验规则: 必须以字母开头 开头的字母不区分大小写

function letterBegin(str){

    return /^[A-z]/.test(str);

}

pureNum 与标点工具

校验字符是否为纯数字(整数) 校验规则: 字符全部为正整数(包含0) 可以以0开头

function pureNum(str) {

    return /^[0-9]*$/.test(str);

}

function anysicPunctuation(str){

    if(!str) return null;

    let arr = str.split('').map(item => {

        return item = '\\' + item;

    });

    return arr.join('|');

}

function getPunctuation(str){

    return anysicPunctuation(str) || '\\~|\\`|\\!|\\@|\\#|\\$|\\%|\\^|\\&|\\*|\\(|\\)|\\-|\\_|\\+|\\=|\\||\\\|\\[|\\]|\\{|\\}|\\;|\\:|\\"|\\\'|\\,|\\<|\\.|\\>|\\/|\\?';

}

function getExcludePunctuation(str){

    let regexp = new RegExp(`[${anysicPunctuation(str)}]`,'g');

    return getPunctuation(' ~`!@#$%^&*()-_+=\[]{};:"\',<.>/?'.replace(regexp,''));

}

getLIPTypes:字母/数字/标点种类数

返回字符串构成种类(字母,数字,标点符号)的数量 LIP缩写的由来:L(letter 字母) + I(uint 数字) + P(punctuation 标点符号) 参数punctuation的说明: punctuation指可接受的标点符号集 若需自定义符号集,例如“仅包含中划线和下划线”,将参数设置为”-_”即可 若不传值或默认为null,则内部默认标点符号集为除空格外的其他英文标点符号:~`!@#$%^&*()-_+=[]{};:”‘, /?

function getLIPTypes(str,punctuation=null){

    let p_regexp = new RegExp('['+getPunctuation(punctuation)+']');

    return /[A-z]/.test(str) + /[0-9]/.test(str) + p_regexp.test(str);

}

pureLIP:密码复杂度

校验字符串构成的种类数量是否大于或等于参数num的值。通常用来校验用户设置的密码复杂程度。

参数 num 只能是 1–3:1 表示至少含字母、数字、标点中的一种,2 至少两种,3 必须三种都有。punctuation 含义同 getLIPTypes。

function pureLIP(str,num=1,punctuation=null){

    let regexp = new RegExp(`[^A-z0-9|${getPunctuation(punctuation)}]`);

    return Boolean(!regexp.test(str) && getLIPTypes(str,punctuation)>= num);

}

四、替换与包含检测

clearSpaces:去空格

清除所有空格

function clearSpaces(str){

    return str.replace(/[ ]/g,'');

}

clearCNChars:去中文

清除所有中文字符(包括中文标点符号)

function clearCNChars(str){

    return str.replace(/[\u4e00-\u9fa5]/g,'');

}

clearCNCharsAndSpaces:去中文和空格

清除所有中文字符及空格

function clearCNCharsAndSpaces(str){

    return str.replace(/[\u4e00-\u9fa5 ]/g,'');

}

clearPunctuation:清英文标点

除保留标点符号集以外,清除其他所有英文的标点符号(含空格) 全部英文标点符号为:~`!@#$%^&*()-_+=[]{};:”‘, /? 参数excludePunctuation指需要保留的标点符号集,例如若传递的值为’_’,即表示清除_以外的其他所有英文标点符号。

function clearPunctuation(str,excludePunctuation=null){

    let regexp = new RegExp(`[${getExcludePunctuation(excludePunctuation)}]`,'g');

    return str.replace(regexp,'');

}

haveSpace:是否含空格

校验是否包含空格

function haveSpace(str) {

    return /[ ]/.test(str);

}

haveCNChars:是否含中文

校验是否包含中文字符(包括中文标点符号)

function haveCNChars(str){

    return /[\u4e00-\u9fa5]/.test(str);

}
函数 典型规则 注意
isTel 1 开头,第二位 3–9,共 11 位 未覆盖近年全部号段扩展
isIDCard 18 位,年份 18/19/2x,月末日粗检 未做校验码
isIP 四段 0–255,禁止 02 这类前导零 不含端口
pureLIP 字母 + 数字 + 标点种类数 用来估密码复杂度
clearCNChars 去掉 \u4e00-\u9fa5 中文标点不在此区间则不会清

LIP 来自 Letter + uint + Punctuation。默认标点集是除空格外的英文标点;自定义时把 punctuation 设成 -_ 即可只认中划线和下划线。

一句话总结:先用正则判断“是不是这种值”,再用 replace 清空格、中文或标点;密码强度看字母、数字、标点凑齐了几种。

转载请注明来源:js常见的输入值校验和替换操作
本文链接地址:https://ai.zhousir.top/?p=2429
回复 取消