1.在utils目录下新建validate.js
数字校验:小数,小数位数,非负数,整数
//小数,小数位数,最大位数
export function checkNum (val, maxlen, decimalsLen) {
let idx = -1;
let value = val.replace(/[^0-9.]/g, '').trim();
if (value == "") {
return value
}
idx = value.indexOf('.');
let raw = value;
if (idx > 0) {
let ext = value.slice(idx + 1, idx + decimalsLen + 1)
if (ext.indexOf('.') > -1) {
ext = ext.slice(0, ext.indexOf('.'));
}
if (ext.length > decimalsLen) {
ext = ext.slice(0, decimalsLen);
}
let fxt = value.slice(0, idx);
if (fxt.length > maxlen) {
fxt = fxt.slice(0, maxlen)
}
value = fxt + '.' + ext;
} else if (idx == 0) {
value = '0.'
} else {
if (value.length > maxlen) {
value = value.slice(0, maxlen)
}
}
return value
}
//非负数
export function isNonNegative(str) {
const reg = /^0$|^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d+)?$/
return reg.test(str)
}
//非负整数
export function isNonNegativeInteger(str) {
const reg = /^\d+$/
return reg.test(str)
}
//正整数
export function isPositiveInteger(str) {
const reg = /^[1-9]\d*$/
return reg.test(str)
}
邮箱校验:
export function isEmail(str) {
const reg = /^(?!.*\.\.)(?!.*\.$)[A-Za-z0-9_.-]+@[a-zA-Z0-9][a-zA-Z0-9.-]*\.[a-zA-Z]{2,}$/
return reg.test(str)
}
手机号校验:
export function isPhone(str) {
const reg = /^1[3456789]\d{9}$/
return reg.test(str)
}
银行账号:
export function isBankAccount(str) {
const reg = /^([0-9]|-){1,30}$/
return reg.test(str)
}
身份证、护照、通行证:
export function isLicenseId(str, type) {
const rule4 = /^[a-zA-Z0-9]{3,21}$/
const rule2 = /^[a-zA-Z0-9]{5,21}$/
const rule = /^\d{15}$|^\d{17}[\dXx]$/
let reg = null
if (type == 4) {
reg = rule4
} else if (type == 2 || type == 3) {
reg = rule2
} else {
reg = rule
}
return reg.test(str)
}
账号密码(数字、字母,8-16位):
export function isPassWordStr(str) {
const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]+$/
return reg.test(str)
}
export function isPassWordLen(str) {
const reg = /^[a-zA-Z\d]{8,16}$/
return reg.test(str)
}