优化预下单选择人数

This commit is contained in:
gyq
2025-12-04 09:39:53 +08:00
parent 00c5987ccc
commit ca829d7f00
6 changed files with 573 additions and 340 deletions

View File

@@ -207,6 +207,12 @@
"style": {
"navigationBarTitleText": "适用门店"
}
},
{
"path": "pages/mesaage/index",
"style": {
"navigationBarTitleText": "消息"
}
}
],
"subPackages": [{

7
pages/mesaage/index.vue Normal file
View File

@@ -0,0 +1,7 @@
<template>
<view class="container">消息</view>
</template>
<script setup></script>
<style scoped lang="scss"></style>

View File

@@ -1,30 +1,24 @@
<template>
<view class="container">
<image class="top_bg" src="https://czg-qr-order.oss-cn-beijing.aliyuncs.com/order/orderAMeal.png"
mode="aspectFill"></image>
<image class="top_bg" src="https://czg-qr-order.oss-cn-beijing.aliyuncs.com/order/orderAMeal.png" mode="aspectFill"></image>
<view class="content_box">
<view class="content">
<view class="title">
<view class="title_text">请选择就餐人数</view>
<view class="title_tabNum">桌号{{shopTable.name}}</view>
<view class="title_tabNum">桌号{{ shopTable.name }}</view>
</view>
<view class="num" :class="{'active':numIndex==-1}">
<view class="item" @click="tabCut(index)" v-for="(item,index) in 9" :key="index">
<view class="num_item" :class="{'active':numIndex==index }">{{index+1}}</view>
<view class="num" :class="{ active: numIndex == -1 }">
<view class="item" @click="tabCut(index)" v-for="(item, index) in 9" :key="index">
<view class="num_item" :class="{ active: numIndex == index }">{{ index + 1 }}</view>
</view>
<view class="item" @click="tabCut(-1)">
<view class="num_item" :style="numIndex==-1?'background-color: #E8AD7B;':'' ">
<up--input v-model="otherNum" @input="isOtherNum" @blur="blur()" border="none" type="nubmer"
maxlength="3" placeholder='请输入..'></up--input>
<view class="num_item" :style="numIndex == -1 ? 'background-color: #E8AD7B;' : ''">
<up--input v-model="otherNum" @input="isOtherNum" @blur="blur()" border="none" type="nubmer" maxlength="3" placeholder="请输入.."></up--input>
</view>
</view>
<!-- <view class="num_item" v-else :class="{'active':numIndex==-1 }"></view> -->
</view>
<view class="startBtn" @click="start">
开始点餐
</view>
<view class="startBtn" @click="start">开始点餐</view>
</view>
</view>
<Loading :isLoading="isLoading" />
@@ -32,241 +26,225 @@
</template>
<script setup>
import {
ref,
onMounted,
getCurrentInstance,
nextTick
} from 'vue'
import { ref, onMounted, getCurrentInstance, nextTick } from 'vue';
import {
onLoad
} from '@dcloudio/uni-app'
import { onLoad } from '@dcloudio/uni-app';
import {
Storelogin
} from '@/stores/user.js';
import { Storelogin } from '@/stores/user.js';
import Loading from '@/components/Loading.vue';
import Loading from '@/components/Loading.vue';
// 获取全局属性
const {
proxy
} = getCurrentInstance();
// 获取全局属性
const { proxy } = getCurrentInstance();
import {
productStore
} from '@/stores/user.js';
import { productStore } from '@/stores/user.js';
// 初始加载中
const isLoading = ref(true);
// 初始加载中
const isLoading = ref(true);
const otherNum = ref('')
const otherNum = ref('');
const numIndex = ref(0)
const numIndex = ref(0);
const dinersNum = ref(1)
const dinersNum = ref(1);
const isOtherNum = (e) => {
otherNum.value = otherNum.value.replace(/\D/g, '')
const isOtherNum = (e) => {
otherNum.value = otherNum.value.replace(/\D/g, '');
};
const tableCode = uni.cache.get('tableCode');
// 切换桌型
const tabCut = (index) => {
console.log(index);
numIndex.value = index;
if (index != -1) {
dinersNum.value = index + 1;
} else {
otherNum.value = otherNum.value == '其他' ? '' : otherNum.value;
}
};
const tableCode = uni.cache.get('tableCode')
const blur = (index) => {
otherNum.value = otherNum.value == '' ? '其他' : otherNum.value;
};
// 切换桌型
const tabCut = (index) => {
console.log(index)
numIndex.value = index;
if (index != -1) {
dinersNum.value = index + 1;
} else {
otherNum.value = otherNum.value == "其他" ? "" : otherNum.value
}
const shopTable = uni.cache.get('shopTable');
const start = async () => {
if (numIndex.value == -1 && (otherNum.value == '其他' || otherNum.value <= 0)) {
uni.showToast({
title: '请选择就餐人数',
icon: 'none'
});
return;
}
const blur = (index) => {
otherNum.value = otherNum.value == "" ? "其他" : otherNum.value
if (numIndex.value == -1 && otherNum.value != '其他') {
dinersNum.value = otherNum.value;
}
const shopTable = uni.cache.get('shopTable')
const start = async () => {
if (numIndex.value == -1 && (otherNum.value == "其他" || otherNum.value <= 0)) {
uni.showToast({
title: '请选择就餐人数',
icon: 'none',
})
return;
}
if (numIndex.value == -1 && otherNum.value != "其他") {
dinersNum.value = otherNum.value
}
if (shopTable.useNum < dinersNum.value && shopTable.useNum > 0) {
uni.showToast({
title: `最多${shopTable.useNum}`,
icon: 'none'
});
return false;
}
uni.cache.set('dinersNum', dinersNum.value)
uni.pro.redirectTo('product/index')
if (shopTable.useNum < dinersNum.value && shopTable.useNum > 0) {
uni.showToast({
title: `最多${shopTable.useNum}`,
icon: 'none'
});
return false;
}
uni.cache.set('dinersNum', dinersNum.value);
uni.pro.redirectTo('product/index');
};
onMounted(async () => {
await proxy.$onLaunched;
// 获取当前页面栈
const pages = getCurrentPages();
// 获取当前页面实例
const currentPage = pages[pages.length - 1];
// 获取页面参数
const options = currentPage.options;
// #ifdef MP-WEIXIN
if (options.q) {
const store = productStore();
await store.scanCodeactions(options.q)
}
// #endif
// #ifdef MP-ALIPAY
if (getApp().globalData.tableCode) {
await store.scanCodeactions(getApp().globalData.tableCode)
}
// #endif
await nextTick()
isLoading.value = uni.cache.get('shopInfo').isTableFee == 0 ? false : true
})
onMounted(async () => {
await proxy.$onLaunched;
// 获取当前页面栈
const pages = getCurrentPages();
// 获取当前页面实例
const currentPage = pages[pages.length - 1];
// 获取页面参数
const options = currentPage.options;
// #ifdef MP-WEIXIN
if (options.q) {
const store = productStore();
await store.scanCodeactions(options.q);
}
// #endif
// #ifdef MP-ALIPAY
if (getApp().globalData.tableCode) {
await store.scanCodeactions(getApp().globalData.tableCode);
}
// #endif
await nextTick();
isLoading.value = uni.cache.get('shopInfo').isTableFee == 0 ? false : true;
});
</script>
<style scoped lang="scss">
page {
// background: #f6f6f6;
}
page {
// background: #f6f6f6;
}
.top_bg {
width: 100%;
height: 100%;
position: absolute;
z-index: 1;
top: 0;
}
.top_bg {
width: 100%;
height: 100%;
position: absolute;
z-index: 1;
top: 0;
}
.content_box {
width: 100%;
padding: 0 28rpx;
position: absolute;
bottom: 148rpx;
}
.content_box {
width: 100%;
padding: 0 28rpx;
position: absolute;
bottom: 148rpx;
}
.content {
width: 100%;
position: relative;
z-index: 2;
.content {
width: 100%;
position: relative;
z-index: 2;
display: flex;
flex-direction: column;
padding: 48rpx 0 32rpx 32rpx;
background: #ffffff;
border-radius: 44rpx 44rpx 44rpx 44rpx;
.title {
display: flex;
flex-direction: column;
padding: 48rpx 0 32rpx 32rpx;
background: #FFFFFF;
border-radius: 44rpx 44rpx 44rpx 44rpx;
align-items: center;
justify-content: space-between;
margin-bottom: 48rpx;
padding-right: 32rpx;
.title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 48rpx;
.title_text {
font-weight: bold;
font-size: 32rpx;
color: #333333;
}
.title_tabNum {
font-weight: 400;
font-size: 28rpx;
color: #666666;
}
}
.num {
display: flex;
flex-wrap: wrap;
.item {
width: 20%;
padding-right: 32rpx;
.title_text {
font-weight: bold;
font-size: 32rpx;
color: #333333;
}
.title_tabNum {
font-weight: 400;
font-size: 28rpx;
color: #666666;
}
}
.num {
display: flex;
flex-wrap: wrap;
.item {
width: 20%;
padding-right: 32rpx;
}
.num_item {
width: 100%;
height: 56rpx;
line-height: 56rpx;
text-align: center;
margin-right: 28rpx;
margin-bottom: 32rpx;
background-color: #FEF4EB;
border-radius: 12rpx;
font-weight: 400;
font-size: 28rpx;
color: #333333;
}
.num_item:nth-child(5n) {
margin-right: 0;
}
::v-deep .u-input {
width: 100%;
height: 56rpx;
line-height: 56rpx;
text-align: center;
margin-bottom: 32rpx;
background-color: #FEF4EB;
border-radius: 12rpx;
}
::v-deep input {
font-weight: 400;
border-radius: 12rpx;
font-size: 28rpx !important;
color: #333333 !important;
text-align: center !important;
background-color: #FEF4EB;
}
.active {
color: #fff;
background-color: #E8AD7B;
}
.num_item {
width: 100%;
height: 56rpx;
line-height: 56rpx;
text-align: center;
margin-right: 28rpx;
margin-bottom: 32rpx;
background-color: #fef4eb;
border-radius: 12rpx;
font-weight: 400;
font-size: 28rpx;
color: #333333;
}
::v-deep .num.active .u-input {
.num_item:nth-child(5n) {
margin-right: 0;
}
::v-deep .u-input {
width: 100%;
height: 56rpx;
line-height: 56rpx;
text-align: center;
margin-bottom: 32rpx;
background-color: #E8AD7B !important;
background-color: #fef4eb;
border-radius: 12rpx;
}
::v-deep .num.active input {
color: #fff !important;
::v-deep input {
font-weight: 400;
border-radius: 12rpx;
background-color: #E8AD7B !important;
font-size: 28rpx !important;
color: #333333 !important;
text-align: center !important;
background-color: #fef4eb;
}
.active {
color: #fff;
background-color: #e8ad7b;
}
}
.startBtn {
::v-deep .num.active .u-input {
width: 100%;
height: 96rpx;
line-height: 96rpx;
height: 56rpx;
line-height: 56rpx;
text-align: center;
background-color: #E8AD7B;
border-radius: 48rpx;
font-weight: bold;
font-size: 32rpx;
color: #FFFFFF;
margin-bottom: 32rpx;
background-color: #e8ad7b !important;
border-radius: 12rpx;
}
</style>
::v-deep .num.active input {
color: #fff !important;
border-radius: 12rpx;
background-color: #e8ad7b !important;
}
}
.startBtn {
width: 100%;
height: 96rpx;
line-height: 96rpx;
text-align: center;
background-color: #e8ad7b;
border-radius: 48rpx;
font-weight: bold;
font-size: 32rpx;
color: #ffffff;
}
</style>

View File

@@ -513,6 +513,42 @@
<recommendGoodsModal v-if="isDataLoaded" @onBuyClick="onBuyClick"></recommendGoodsModal>
<goodsModal></goodsModal>
<xbSwiperPreview :visable="showPrveImg" :imgs="prveImgsList" @update:visable="showPrveImg = $event"></xbSwiperPreview>
<!-- 显示选择人数popup -->
<u-popup mode="bottom" :safe-area-inset-bottom="false" :show="showTableInfoPeopleNumPopup">
<view class="select_num_wrap">
<image class="top_bg" src="https://czg-qr-order.oss-cn-beijing.aliyuncs.com/order/orderAMeal.png" mode="aspectFill"></image>
<view class="sn-bnottom">
<view class="sn-header">
<text class="t1">请选择就餐人数</text>
<text class="t2">桌号{{ shopTable.name }}</text>
</view>
<view class="sn-num-wrap">
<view class="sn-num">
<view
class="item"
:class="{ active: tableInfoPeopleActive == index }"
v-for="(item, index) in 10"
:key="item"
@click="tableInfoPeopleNumHandle(item, index)"
>
<text class="t">{{ item }}</text>
</view>
</view>
<view class="input">
<u-input v-model="tableInfoPeopleNum" :maxlength="2" placeholder="请输入自定义人数" clearable @change="tableInfoPeopleNumInput"></u-input>
</view>
</view>
<view class="sn-footer-wrap">
<view class="btn">
<u-button plain shape="circle" @click="closeTableInfoPeopleNum">取消</u-button>
</view>
<view class="btn">
<u-button type="primary" shape="circle" @click="tableInfoPeopleNumConfirm">确认</u-button>
</view>
</view>
</view>
</view>
</u-popup>
</view>
</template>
@@ -541,6 +577,7 @@ import Loading from '@/components/Loading.vue';
import dayjs from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween';
dayjs.extend(isBetween);
import { filterNumberInput } from '@/utils/util.js';
//点单智能推荐
function onBuyClick(item) {
@@ -1461,8 +1498,19 @@ async function onMessage(Message) {
// 转桌成功
if (Message.operate_type == 'rottable' && Message.status == 1) {
console.log('转桌成功了');
uni.showToast({
title: '扫码成功,请下单',
icon: 'none'
});
orderType.value = 'scan';
uni.cache.set('tableCode', Message.data.new_table_code);
if (showTableInfoPeopleNumPopup.value == true) {
showTableInfoPeopleNumPopup.value = false;
}
websocketsendMessage(options.initMessage);
}
@@ -1860,27 +1908,78 @@ provide('shopInfo', shopInfo);
const orderType = ref('scan');
// 扫码下单
// 台桌信息
const showTableInfoPeopleNumPopup = ref(false);
const tableInfo = ref('');
// 选择的人数
const tableInfoPeopleActive = ref(-1);
const tableInfoPeopleNum = ref('');
// 选择人数
function tableInfoPeopleNumHandle(num, index) {
tableInfoPeopleActive.value = index;
tableInfoPeopleNum.value = num;
}
// 人数输入框
function tableInfoPeopleNumInput(e) {
tableInfoPeopleActive.value = -1;
setTimeout(() => {
tableInfoPeopleNum.value = filterNumberInput(e, 1);
}, 50);
}
// 取消选择人数
function closeTableInfoPeopleNum() {
showTableInfoPeopleNumPopup.value = false;
tableInfoPeopleActive.value = -1;
tableInfoPeopleNum.value = '';
}
// 确认选择人数
function tableInfoPeopleNumConfirm() {
uni.cache.set('dinersNum', tableInfoPeopleNum.value);
startUseTable();
}
// 开始换桌
function startUseTable() {
const shopInfo = uni.cache.get('shopInfo');
const oldTableCode = uni.cache.get('tableCode');
const cartIds = cartStore.carts.map((item) => item.id);
const data = {
type: 'onboc',
operate_type: 'rottable',
account: shopInfo.phone,
table_code: oldTableCode,
new_table_code: tableInfo.value.tableCode,
cart_id: cartIds,
shop_id: shopInfo.id
};
websocketsendMessage(data);
}
// 预点单扫码下单
function beforehandHandle() {
uni.scanCode({
success(res) {
const shopInfo = uni.cache.get('shopInfo');
const oldTableCode = uni.cache.get('tableCode');
const newTableCode = userStore.getQueryString(res.result, 'code');
const cartIds = cartStore.carts.map((item) => item.id);
success: async (res) => {
try {
const newTableCode = userStore.getQueryString(res.result, 'code');
const data = {
type: 'onboc',
operate_type: 'rottable',
account: shopInfo.phone,
table_code: oldTableCode,
new_table_code: newTableCode,
cart_id: cartIds,
shop_id: shopInfo.id
};
console.log('scanCode.data===', data);
// return;
websocketsendMessage(data);
if (shopInfo.isTableFee) {
startUseTable();
} else {
await userStore.actionsproductqueryShop(newTableCode);
tableInfo.value = uni.cache.get('shopTable');
showTableInfoPeopleNumPopup.value = true;
}
} catch (error) {
console.log(error);
}
}
});
}
@@ -2961,4 +3060,81 @@ function toHistory() {
z-index: 9;
color: #fff;
}
.select_num_wrap {
width: 100vw;
height: 100vh;
position: relative;
.top_bg {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
.sn-bnottom {
width: 90vw;
border-radius: 20upx;
background-color: #fff;
position: absolute;
left: 5vw;
bottom: 20vw;
z-index: 2;
.sn-header {
height: 120upx;
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid #ececec;
padding: 0 28upx;
.t1 {
color: #333;
font-size: 32upx;
}
.t2 {
color: #999;
font-size: 28upx;
}
}
.sn-num-wrap {
padding: 38upx 28upx;
border-bottom: 1px solid #ececec;
.sn-num {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 14px;
.item {
height: 40px;
border-radius: 6px;
background-color: #fef4eb;
display: flex;
align-items: center;
justify-content: center;
&.active {
background-color: #e8ad7b;
.t {
color: #fff;
}
}
.t {
color: #333333;
font-size: 32upx;
}
}
}
.input {
display: flex;
padding-top: 28upx;
}
}
.sn-footer-wrap {
display: flex;
gap: 28upx;
padding: 28upx;
.btn {
flex: 1;
}
}
}
}
</style>

View File

@@ -1,7 +1,7 @@
<template>
<view class="container">
<view class="header-wrap">
<view class="u-flex" style="justify-content: flex-end;">
<view class="u-flex" style="justify-content: flex-end">
<view @click="toExchangeCode" class="color-333 font-12 u-m-b-26 font-700">优惠券兑换码</view>
</view>
<view class="search-wrap">
@@ -140,10 +140,10 @@ onReachBottom(() => {
getCouponList();
}
});
function toExchangeCode(){
function toExchangeCode() {
uni.navigateTo({
url: '/user/exchange/index'
})
});
}
const showDetail = ref(false);
const selectListItem = ref('');
@@ -223,7 +223,7 @@ async function getCouponList() {
userId: uni.cache.get('userInfo').id,
name: querForm.value.searchValue,
status: statusList.value[querForm.value.statusActiveIndex].value,
// shopId: querForm.value.shopId ? querForm.value.shopId : uni.cache.get('shopId'),
shopId: querForm.value.shopId ? querForm.value.shopId : uni.cache.get('shopId'),
page: list.page,
size: list.size
});
@@ -426,7 +426,7 @@ page {
}
}
.list-wrap {
padding-top: 28upx;
padding-top: 88upx;
.item {
border-radius: 18upx;
background-color: #fff;

View File

@@ -4,53 +4,65 @@
* @returns {string} 脱敏后手机号
*/
export function desensitizePhone(phone) {
// 1. 提取纯数字(过滤非数字字符)
const purePhone = (phone || "").replace(/[^\d]/g, "");
// 2. 边界判断非11位手机号返回原字符串或自定义提示
if (purePhone.length !== 11) {
console.warn("手机号格式不正确需11位纯数字");
return phone; // 或返回 ''、'手机号格式错误' 等
}
// 3. 脱敏前3位 + **** + 后4位
return purePhone.replace(/(\d{3})(\d{4})(\d{4})/, "$1****$3");
}
// 1. 提取纯数字(过滤非数字字符)
const purePhone = (phone || "").replace(/[^\d]/g, "");
/**
// 2. 边界判断非11位手机号返回原字符串或自定义提示
if (purePhone.length !== 11) {
console.warn("手机号格式不正确需11位纯数字");
return phone; // 或返回 ''、'手机号格式错误' 等
}
// 3. 脱敏前3位 + **** + 后4位
return purePhone.replace(/(\d{3})(\d{4})(\d{4})/, "$1****$3");
}
/**
* 姓名合法性校验
* @param {string} name - 待校验的姓名
* @returns {Object} 校验结果:{ valid: boolean, msg: string }
*/
export function validateName(name) {
// 1. 空值校验
if (!name || name.trim() === '') {
return { valid: false, msg: '姓名不能为空' };
}
const pureName = name.trim();
// 1. 空值校验
if (!name || name.trim() === '') {
return {
valid: false,
msg: '姓名不能为空'
};
}
const pureName = name.trim();
// 2. 长度校验2-6位含少数民族中间点
if (pureName.length < 2 || pureName.length > 6) {
return { valid: false, msg: '姓名长度应为2-6位' };
}
// 2. 长度校验2-6位含少数民族中间点
if (pureName.length < 2 || pureName.length > 6) {
return {
valid: false,
msg: '姓名长度应为2-6位'
};
}
// 3. 正则校验:仅允许中文、少数民族中间点(·),且中间点不能在开头/结尾
// 中文范围:[\u4e00-\u9fa5],中间点:[\u00b7]Unicode 标准中间点,非小数点)
const nameReg = /^[\u4e00-\u9fa5]+([\u00b7][\u4e00-\u9fa5]+)*$/;
if (!nameReg.test(pureName)) {
return {
valid: false,
msg: '姓名仅支持中文和少数民族中间点(·),且不能包含数字、字母或特殊符号'
};
}
// 3. 正则校验:仅允许中文、少数民族中间点(·),且中间点不能在开头/结尾
// 中文范围:[\u4e00-\u9fa5],中间点:[\u00b7]Unicode 标准中间点,非小数点)
const nameReg = /^[\u4e00-\u9fa5]+([\u00b7][\u4e00-\u9fa5]+)*$/;
if (!nameReg.test(pureName)) {
return {
valid: false,
msg: '姓名仅支持中文和少数民族中间点(·),且不能包含数字、字母或特殊符号'
};
}
// 4. 额外限制:中间点不能连续(如“李··四”)
if (/[\u00b7]{2,}/.test(pureName)) {
return { valid: false, msg: '姓名中的中间点(·)不能连续' };
}
// 4. 额外限制:中间点不能连续(如“李··四”)
if (/[\u00b7]{2,}/.test(pureName)) {
return {
valid: false,
msg: '姓名中的中间点(·)不能连续'
};
}
// 校验通过
return { valid: true, msg: '姓名格式合法' };
// 校验通过
return {
valid: true,
msg: '姓名格式合法'
};
}
/**
@@ -60,84 +72,138 @@ export function validateName(name) {
* info 可选返回:{ birthDate: string, gender: string }(出生日期、性别)
*/
export function validateIdCard(idCard) {
// 1. 空值校验
if (!idCard || idCard.trim() === '') {
return { valid: false, msg: '身份证号码不能为空' };
}
const pureIdCard = idCard.trim().toUpperCase(); // 统一转为大写处理X
// 1. 空值校验
if (!idCard || idCard.trim() === '') {
return {
valid: false,
msg: '身份证号码不能为空'
};
}
const pureIdCard = idCard.trim().toUpperCase(); // 统一转为大写处理X
// 2. 格式校验18位或15位
const id18Reg = /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))((0[1-9])|([12]\d)|(3[01]))\d{3}([0-9]|X)$/;
const id15Reg = /^[1-9]\d{5}\d{2}((0[1-9])|(1[0-2]))((0[1-9])|([12]\d)|(3[01]))\d{3}$/;
if (!id18Reg.test(pureIdCard) && !id15Reg.test(pureIdCard)) {
return {
valid: false,
msg: '身份证号码格式错误需18位最后一位可含X或15位纯数字'
};
}
// 2. 格式校验18位或15位
const id18Reg = /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))((0[1-9])|([12]\d)|(3[01]))\d{3}([0-9]|X)$/;
const id15Reg = /^[1-9]\d{5}\d{2}((0[1-9])|(1[0-2]))((0[1-9])|([12]\d)|(3[01]))\d{3}$/;
// 3. 提取出生日期并校验合法性
let birthDateStr, birthDate;
if (pureIdCard.length === 18) {
// 18位第7-14位为出生日期YYYYMMDD
birthDateStr = pureIdCard.slice(6, 14);
birthDate = new Date(`${birthDateStr.slice(0,4)}-${birthDateStr.slice(4,6)}-${birthDateStr.slice(6,8)}`);
} else {
// 15位第7-12位为出生日期YYMMDD补全为YYYYMMDD19xx或20xx默认19xx
const year = `19${pureIdCard.slice(6, 8)}`;
const month = pureIdCard.slice(8, 10);
const day = pureIdCard.slice(10, 12);
birthDateStr = `${year}${month}${day}`;
birthDate = new Date(`${year}-${month}-${day}`);
}
if (!id18Reg.test(pureIdCard) && !id15Reg.test(pureIdCard)) {
return {
valid: false,
msg: '身份证号码格式错误需18位最后一位可含X或15位纯数字'
};
}
// 校验出生日期有效性如20230230 → 日期对象会是Invalid Date
if (
isNaN(birthDate.getTime()) ||
birthDateStr.slice(0,4) !== birthDate.getFullYear().toString() ||
birthDateStr.slice(4,6) !== (birthDate.getMonth() + 1).toString().padStart(2, '0') ||
birthDateStr.slice(6,8) !== birthDate.getDate().toString().padStart(2, '0')
) {
return { valid: false, msg: '身份证中的出生日期无效' };
}
// 3. 提取出生日期并校验合法性
let birthDateStr, birthDate;
if (pureIdCard.length === 18) {
// 18位第7-14位为出生日期YYYYMMDD
birthDateStr = pureIdCard.slice(6, 14);
birthDate = new Date(`${birthDateStr.slice(0,4)}-${birthDateStr.slice(4,6)}-${birthDateStr.slice(6,8)}`);
} else {
// 15位第7-12位为出生日期YYMMDD补全为YYYYMMDD19xx或20xx默认19xx
const year = `19${pureIdCard.slice(6, 8)}`;
const month = pureIdCard.slice(8, 10);
const day = pureIdCard.slice(10, 12);
birthDateStr = `${year}${month}${day}`;
birthDate = new Date(`${year}-${month}-${day}`);
}
// 4. 18位身份证额外校验校验码合法性加权算法
if (pureIdCard.length === 18) {
// 加权因子
const weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
// 校验码对应值0-10 → 10对应X
const checkCodeMap = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
// 计算前17位与加权因子的乘积和
let sum = 0;
for (let i = 0; i < 17; i++) {
sum += parseInt(pureIdCard[i]) * weightFactors[i];
}
// 计算预期校验码
const expectedCheckCode = checkCodeMap[sum % 11];
// 对比实际校验码(最后一位)
if (pureIdCard[17] !== expectedCheckCode) {
return { valid: false, msg: '身份证校验码错误,可能是无效身份证' };
}
}
// 校验出生日期有效性如20230230 → 日期对象会是Invalid Date
if (
isNaN(birthDate.getTime()) ||
birthDateStr.slice(0, 4) !== birthDate.getFullYear().toString() ||
birthDateStr.slice(4, 6) !== (birthDate.getMonth() + 1).toString().padStart(2, '0') ||
birthDateStr.slice(6, 8) !== birthDate.getDate().toString().padStart(2, '0')
) {
return {
valid: false,
msg: '身份证中的出生日期无效'
};
}
// 5. 可选提取性别18位第17位15位第15位奇数=男,偶数=女
let gender = '';
if (pureIdCard.length === 18) {
const genderCode = parseInt(pureIdCard[16]);
gender = genderCode % 2 === 1 ? '男' : '女';
} else {
const genderCode = parseInt(pureIdCard[14]);
gender = genderCode % 2 === 1 ? '男' : '女';
}
// 4. 18位身份证额外校验校验码合法性加权算法
if (pureIdCard.length === 18) {
// 加权因子
const weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
// 校验码对应值0-10 → 10对应X
const checkCodeMap = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
// 计算前17位与加权因子的乘积和
let sum = 0;
for (let i = 0; i < 17; i++) {
sum += parseInt(pureIdCard[i]) * weightFactors[i];
}
// 计算预期校验码
const expectedCheckCode = checkCodeMap[sum % 11];
// 对比实际校验码(最后一位)
if (pureIdCard[17] !== expectedCheckCode) {
return {
valid: false,
msg: '身份证校验码错误,可能是无效身份证'
};
}
}
// 校验通过,返回额外信息(出生日期、性别
return {
valid: true,
msg: '身份证号码合法',
info: {
birthDate: `${birthDate.getFullYear()}-${(birthDate.getMonth() + 1).toString().padStart(2, '0')}-${birthDate.getDate().toString().padStart(2, '0')}`,
gender: gender
}
};
// 5. 可选提取性别18位第17位15位第15位奇数=男,偶数=女
let gender = '';
if (pureIdCard.length === 18) {
const genderCode = parseInt(pureIdCard[16]);
gender = genderCode % 2 === 1 ? '男' : '女';
} else {
const genderCode = parseInt(pureIdCard[14]);
gender = genderCode % 2 === 1 ? '男' : '女';
}
// 校验通过,返回额外信息(出生日期、性别)
return {
valid: true,
msg: '身份证号码合法',
info: {
birthDate: `${birthDate.getFullYear()}-${(birthDate.getMonth() + 1).toString().padStart(2, '0')}-${birthDate.getDate().toString().padStart(2, '0')}`,
gender: gender
}
};
}
/**
* 过滤输入,只允许数字和最多两位小数
* @param {string} value - 输入框当前值
* @param {boolean} isIntegerOnly - 是否只允许正整数无小数点开启时最小值为1
* @returns {string} 过滤后的合法值
*/
export function filterNumberInput(value, isIntegerOnly = false) {
// 第一步就过滤所有非数字和非小数点的字符(包括字母)
let filtered = value.replace(/[^\d.]/g, "");
// 整数模式处理
if (isIntegerOnly !== false) {
// 移除所有小数点
filtered = filtered.replace(/\./g, "");
// 处理前导零
filtered = filtered.replace(/^0+(\d)/, "$1") || filtered;
// 空值处理(允许临时删除)
if (filtered === "") {
return "";
}
// 最小值限制
if (filtered === isIntegerOnly || parseInt(filtered, 10) < isIntegerOnly) {
return isIntegerOnly;
}
return filtered;
}
// 小数模式处理
const parts = filtered.split(".");
if (parts.length > 1) {
filtered = parts[0] + "." + (parts[1].substring(0, 2) || "");
}
// 处理前导零
if (filtered.startsWith("0") && filtered.length > 1 && !filtered.startsWith("0.")) {
filtered = filtered.replace(/^0+(\d)/, "$1");
}
return filtered;
}