form表单常用方法
手机号校验
export const checkPhone = (data) => {
let value = true
let code = /^1[3456789]\d{9}$/;
if (!code.test(data)) {
value = false;
console.log('手机号格式错误')
}
return value
}
电子邮箱校验
export const checkEmail = (data) => {
let value = true
let code = /(^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$)/;
if (!code.test(data)) {
value = false;
console.log('电子邮箱格式错误')
}
return value
}
邮编校验
export const checkZipCode = (data) => {
let value = true
let code = /(^[0-9]{6}$)|(^$)/;
if (!code.test(data)) {
value = false;
console.log('邮编格式错误')
}
return value
}
姓名校验
export const checkName = (data) => {
let value = true
let code = /^[\u4E00-\u9FA5]+(·[\u4E00-\u9FA5]+)*$/;
if (!code.test(data)) {
value = false;
console.log('姓名格式错误')
}
return value
}
身份证校验,并提取年龄、生日、性别信息
注意:此方法只能粗略校验,不够细致
export const checkIdNum = (data) => {
let info = {
age: '',
sex: '',
sexName: '',
brith: '',
value: ''
}
let code =
/(^[1-9]\d{5}[1-2]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}(\d|X|x)$)|(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)/;
if (!code.test(data)) {
info.value = false
console.log('身份证号格式错误')
} else {
// 提取性别信息,0表示男性,1表示女性
let sexs = data.substring(16, 17)
if (sexs % 2 === 0) {
info.sex = 1
info.sexName = '女'
} else {
info.sex = 0
info.sexName = '男'
}
// 提取生日信息
info.brith = data.substring(6, 10) + '-' + data.substring(10, 12) + '-' + data.substring(12, 14);
// 计算年龄
let briths = new Date(info.brith)
let now = new Date()
info.age = now.getFullYear() -
briths.getFullYear() -
(now.getMonth() < briths.getMonth() ||
(now.getMonth() == briths.getMonth() &&
now.getDate() < briths.getDate()) ?
1 :
0);
// 身份证号是否符合格式
info.value = true;
}
return info
}
根据出生日期计算年龄
注意:需传入 yyyy-mm-dd | yyyy/mm/dd 格式的值
export const obtainAge = (data) => {
let briths = new Date(data)
let now = new Date()
let age = now.getFullYear() -
briths.getFullYear() -
(now.getMonth() < briths.getMonth() ||
(now.getMonth() == briths.getMonth() &&
now.getDate() < briths.getDate()) ?
1 :
0);
return age
}
数字添加单位(万、亿)
注意:传入的值需要能被parseFloat()方法转换
export const countUnit = (value) => {
let count = parseFloat(value)
let detail = {
value: 0,
unit: ''
}
if (count < 10000) {
detail.value = count;
detail.unit = ''
} else if (10000 <= count < 100000000) {
detail.value = (count / 10000).toFixed(2);
detail.unit = '万'
} else {
detail.value = (count / 100000000).toFixed(2);
detail.unit = '亿'
}
return detail
}