完善表单校验与公共数据逻辑

Co-Authored-By: Kimi-K3.1-Pro <noreply@moonshot.ai>
This commit is contained in:
lik
2026-10-24 18:49:02 +08:00
committed by trae-solo-agent
co-authored by Kimi-K3.1-Pro
parent d731fc1da3
commit a45a3d7a86
18 changed files with 496 additions and 336 deletions
+147 -136
View File
@@ -1,24 +1,25 @@
const API = require('../../utils/api.js')
const { parseDate, formatDate } = require('../../utils/date.js')
const { setUnsavedGuard } = require('../../utils/form.js')
// 性别选项,与后端 schema 的 male / female 对应
const SEX_OPTIONS = [{
value: 'male',
label: '男'
},
{
value: 'female',
label: '女'
}
const SEX_OPTIONS = [
{ value: 'male', label: '男' },
{ value: 'female', label: '女' }
]
const MOBILE_REGEX = /^1[3-9]\d{9}$/
const ID_NUMBER_REGEX = /^\d{17}[\dXx]$/
Page({
data: {
id: '',
isEdit: false,
saving: false,
loading: false,
loadError: '',
today: '',
errors: {},
sexOptions: SEX_OPTIONS,
form: {
name: '',
@@ -34,11 +35,13 @@ Page({
onLoad(options) {
const id = options.id || ''
this.unsavedGuardActive = false
this.initialFormSnapshot = ''
this.setData({
id,
isEdit: !!id,
today: this.formatDate(new Date())
today: formatDate(new Date())
})
wx.setNavigationBarTitle({
@@ -47,59 +50,71 @@ Page({
if (id) {
this.loadProfile(id)
} else {
this.captureInitialForm()
}
},
formatDate(date) {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
onUnload() {
if (this.unsavedGuardActive) setUnsavedGuard(false)
},
// 编辑模式:读取档案详情回填表单
loadProfile(id) {
API.healthProfile.getMyProfileById(id)
.then((res) => {
if (res.code !== 0) {
wx.showToast({
title: res.msg || '加载失败',
icon: 'none'
})
return
}
const detail = (res.data && res.data.profile) || {}
const profile = detail.profile || {}
const health = detail.health || {}
captureInitialForm() {
this.initialFormSnapshot = JSON.stringify(this.data.form)
this.syncUnsavedGuard()
},
this.setData({
form: {
name: profile.name || '',
sex: profile.sex || '',
birth: profile.birth || '',
mobile: profile.mobile || '',
idnumber: profile.idnumber || '',
// 身高的 schema 默认值是 0,0 视为未填写,回填成空串而不是 "0"
height: health.height ? String(health.height) : '',
weight: health.weight ? String(health.weight) : '',
remark: health.remark || ''
}
})
})
.catch((err) => {
console.log('获取就诊人信息失败', err)
wx.showToast({
title: '网络请求失败',
icon: 'none'
})
syncUnsavedGuard() {
const dirty = JSON.stringify(this.data.form) !== this.initialFormSnapshot
if (dirty === this.unsavedGuardActive) return
this.unsavedGuardActive = dirty
setUnsavedGuard(dirty)
},
// 编辑模式:读取档案详情回填表单;失败时不能用空表单冒充已加载。
async loadProfile(id) {
this.setData({ loading: true, loadError: '' })
try {
const res = await API.healthProfile.getMyProfileById(id)
if (res.code !== 0) throw new Error(res.msg || '就诊人信息加载失败')
const detail = (res.data && res.data.profile) || {}
const profile = detail.profile || {}
const health = detail.health || {}
this.setData({
form: {
name: profile.name || '',
sex: profile.sex || '',
birth: formatDate(profile.birth),
mobile: profile.mobile || '',
idnumber: profile.idnumber || '',
// 身高的 schema 默认值是 0,0 视为未填写,回填成空串而不是 "0"
height: health.height ? String(health.height) : '',
weight: health.weight ? String(health.weight) : '',
remark: health.remark || ''
}
})
this.captureInitialForm()
} catch (err) {
console.log('获取就诊人信息失败', err)
this.setData({ loadError: err.message || '网络请求失败,请重试' })
} finally {
this.setData({ loading: false })
}
},
retryLoad() {
if (this.data.id) this.loadProfile(this.data.id)
},
onFieldInput(e) {
const field = e.currentTarget.dataset.field
this.setData({
[`form.${field}`]: e.detail.value
[`form.${field}`]: e.detail.value,
[`errors.${field}`]: ''
})
this.syncUnsavedGuard()
},
onSexSelect(e) {
@@ -108,80 +123,97 @@ Page({
this.setData({
'form.sex': this.data.form.sex === sex ? '' : sex
})
this.syncUnsavedGuard()
},
onBirthChange(e) {
this.setData({
'form.birth': e.detail.value
'form.birth': e.detail.value,
'errors.birth': ''
})
this.syncUnsavedGuard()
},
// 表单校验,返回错误提示文案;通过校验返回空字符串
validateOptionalNumber(value, min, max) {
if (!value.trim()) return true
const number = Number(value)
return Number.isFinite(number) && number >= min && number <= max
},
// 返回字段错误表,WXML 在对应字段下展示,保存时同时提示首个错误。
validate() {
const {
name,
mobile
} = this.data.form
const { name, mobile, birth, idnumber, height, weight } = this.data.form
const errors = {}
if (!name.trim()) {
return '请输入就诊人姓名'
}
if (!name.trim()) errors.name = '请输入就诊人姓名'
if (!mobile.trim()) {
return '请输入联系电话'
errors.mobile = '请输入联系电话'
} else if (!MOBILE_REGEX.test(mobile.trim())) {
errors.mobile = '请输入正确的 11 位手机号'
}
if (!MOBILE_REGEX.test(mobile.trim())) {
return '请输入正确的手机号'
if (birth) {
const birthDate = parseDate(birth)
if (!birthDate) {
errors.birth = '请选择有效的出生日期'
} else if (birthDate < parseDate('1900-01-01') || birthDate > parseDate(this.data.today)) {
errors.birth = '出生日期需在 1900-01-01 至今天之间'
}
}
return ''
if (idnumber.trim()) {
const value = idnumber.trim()
if (!ID_NUMBER_REGEX.test(value)) {
errors.idnumber = '请输入 18 位身份证号,末位可为 X'
} else {
const idBirth = `${value.slice(6, 10)}-${value.slice(10, 12)}-${value.slice(12, 14)}`
if (!parseDate(idBirth)) errors.idnumber = '身份证号中的出生日期无效'
}
}
if (!this.validateOptionalNumber(height, 30, 250)) {
errors.height = '身高需为 30–250 cm 的数字'
}
if (!this.validateOptionalNumber(weight, 2, 300)) {
errors.weight = '体重需为 2–300 kg 的数字'
}
return errors
},
onSave() {
if (this.data.saving) {
async onSave() {
if (this.data.saving) return
const errors = this.validate()
const firstError = Object.values(errors)[0]
this.setData({ errors })
if (firstError) {
wx.showToast({ title: firstError, icon: 'none' })
return
}
const errorMessage = this.validate()
if (errorMessage) {
wx.showToast({
title: errorMessage,
icon: 'none'
})
return
}
const { name, sex, birth, mobile, idnumber, height, weight, remark } = this.data.form
// 可选数值留空才写 0;所有非空值已通过校验,不再用 || 0 吞掉非法输入。
const heightNum = height.trim() ? Number(height) : 0
const weightNum = weight.trim() ? Number(weight) : 0
const {
name,
sex,
birth,
mobile,
idnumber,
height,
weight,
remark
} = this.data.form
// schema 里身高/体重是 Number,未填按 0(Number('') 即 0,非法输入 NaN 也回落 0)
const heightNum = Number(height) || 0
const weightNum = Number(weight) || 0
// 新增用嵌套对象(schema 的 new Model 需要嵌套结构);
// 更新用点号路径(schema 更新姓名时会额外写 profile.pinyin,整体替换 profile 会冲突)
// 新增用嵌套对象;更新用点号路径,避免与后端 profile.pinyin 的额外写入冲突。
const payload = this.data.isEdit ? {
'profile.name': name.trim(),
'profile.sex': sex,
'profile.birth': birth,
'profile.mobile': mobile.trim(),
'profile.idnumber': idnumber.trim(),
'profile.idnumber': idnumber.trim().toUpperCase(),
'health.height': heightNum,
'health.weight': weightNum,
'health.remark': remark.trim()
} : {
profile: {
name: name.trim(),
sex: sex,
birth: birth,
sex,
birth,
mobile: mobile.trim(),
idnumber: idnumber.trim()
idnumber: idnumber.trim().toUpperCase()
},
health: {
height: heightNum,
@@ -190,53 +222,32 @@ Page({
}
}
this.setData({
saving: true
})
wx.showLoading({
title: '保存中...'
})
this.setData({ saving: true })
wx.showLoading({ title: '保存中...' })
const request = this.data.isEdit ?
API.healthProfile.updateMyProfile(this.data.id, payload) :
API.healthProfile.createMyProfile(payload)
try {
const request = this.data.isEdit
? API.healthProfile.updateMyProfile(this.data.id, payload)
: API.healthProfile.createMyProfile(payload)
const res = await request
if (res.code !== 0) {
wx.showToast({ title: res.msg || '保存失败', icon: 'none' })
return
}
request
.then((res) => {
wx.hideLoading()
if (res.code !== 0) {
wx.showToast({
title: res.msg || '保存失败',
icon: 'none'
})
return
}
wx.showToast({
title: '保存成功',
icon: 'success'
})
setTimeout(() => {
wx.navigateBack()
}, 800)
})
.catch((err) => {
wx.hideLoading()
console.log('保存就诊人失败', err)
wx.showToast({
title: '网络请求失败',
icon: 'none'
})
})
.finally(() => {
this.setData({
saving: false
})
})
this.captureInitialForm()
wx.showToast({ title: '保存成功', icon: 'success' })
setTimeout(() => wx.navigateBack(), 800)
} catch (err) {
console.log('保存就诊人失败', err)
wx.showToast({ title: '网络请求失败', icon: 'none' })
} finally {
wx.hideLoading()
this.setData({ saving: false })
}
},
// 本页是就诊人档案表单(姓名 / 手机号 / 身份证号),转发卡片不指向本页,
// 统一落到首页,避免好友打开一个需要登录的空表单;
// 也不提供朋友圈分享——朋友圈只能分享当前页 URL,会把档案页地址带出去
// 转发卡片统一落到首页,避免好友打开需要登录的空表单。
onShareAppMessage() {
return {
title: '暖橙陪诊 · 专业陪诊服务',
+22 -6
View File
@@ -1,12 +1,23 @@
<view class="container">
<!-- 编辑模式先等待档案回填;加载失败时展示真实错误态,不露出可保存的空表单。 -->
<view class="page-state" wx:if="{{loading}}">
<t-loading size="48rpx" />
<text class="page-state-text">正在加载就诊人信息</text>
</view>
<view class="page-state" wx:if="{{isEdit && !loading && loadError}}">
<text class="page-state-text">{{loadError}}</text>
<view class="page-retry" bindtap="retryLoad">重新加载</view>
</view>
<!-- 基本信息:通栏白块(白面 + 上下 2rpx 发丝线 + 中性阴影,圆角 0),
行内标签左走 --muted、值右走 --ink 700,与「个人信息」「邮寄地址」同一表单语言 -->
<view class="form-card">
<view class="form-card" wx:if="{{!loading && !loadError}}">
<view class="form-row">
<text class="form-label">姓名</text>
<input class="form-input" value="{{form.name}}" placeholder="请输入就诊人姓名" placeholder-class="form-placeholder"
maxlength="20" data-field="name" bindinput="onFieldInput" />
<text class="field-error" wx:if="{{errors.name}}">{{errors.name}}</text>
</view>
<view class="form-row">
@@ -28,34 +39,39 @@
{{form.birth || '请选择出生年月'}}
</view>
</picker>
<text class="field-error" wx:if="{{errors.birth}}">{{errors.birth}}</text>
</view>
<view class="form-row">
<text class="form-label">联系电话</text>
<input class="form-input" value="{{form.mobile}}" type="number" placeholder="用于陪诊师联系您" placeholder-class="form-placeholder"
maxlength="11" data-field="mobile" bindinput="onFieldInput" />
<text class="field-error" wx:if="{{errors.mobile}}">{{errors.mobile}}</text>
</view>
<view class="form-row form-row-last">
<text class="form-label">证件号</text>
<input class="form-input" value="{{form.idnumber}}" placeholder="选填,用于医院建档取号" placeholder-class="form-placeholder"
maxlength="30" data-field="idnumber" bindinput="onFieldInput" />
maxlength="18" data-field="idnumber" bindinput="onFieldInput" />
<text class="field-error" wx:if="{{errors.idnumber}}">{{errors.idnumber}}</text>
</view>
</view>
<!-- 健康信息:身高/体重是短输入,沿用行内表单语言(标签左、值右);健康备注是多行输入,
无法与标签同排,故留在本块末尾单独一排——标签在上、文本域在下、字数右下 -->
<view class="form-card">
<view class="form-card" wx:if="{{!loading && !loadError}}">
<view class="form-row">
<text class="form-label">身高(cm)</text>
<input class="form-input" value="{{form.height}}" type="digit" placeholder="选填,单位 cm" placeholder-class="form-placeholder"
maxlength="5" data-field="height" bindinput="onFieldInput" />
<text class="field-error" wx:if="{{errors.height}}">{{errors.height}}</text>
</view>
<view class="form-row">
<text class="form-label">体重(kg)</text>
<input class="form-input" value="{{form.weight}}" type="digit" placeholder="选填,单位 kg" placeholder-class="form-placeholder"
maxlength="5" data-field="weight" bindinput="onFieldInput" />
<text class="field-error" wx:if="{{errors.weight}}">{{errors.weight}}</text>
</view>
<view class="form-remark">
@@ -66,14 +82,14 @@
</view>
</view>
<view class="tips">
<view class="tips" wx:if="{{!loading && !loadError}}">
<t-icon name="lock-on" class="tips-icon" size="26rpx" />
<text class="tips-text">信息仅用于陪诊服务,我们会严格保密</text>
</view>
<!-- 保存是本页唯一的实心暖橙块,独占「全页同类实心块不超过一处」的额度 -->
<view class="footer-bar">
<view class="footer-bar" wx:if="{{!loading && !loadError}}">
<button class="primary-btn {{saving ? 'primary-btn-disabled' : ''}}" bindtap="onSave">保存</button>
</view>
</view>
</view>
+36
View File
@@ -11,6 +11,32 @@ page {
padding: 40rpx 32rpx calc(180rpx + env(safe-area-inset-bottom));
}
/* ===== 加载与失败状态 ===== */
.page-state {
display: flex;
flex-direction: column;
align-items: center;
padding: 120rpx 32rpx;
}
.page-state-text {
margin-top: 20rpx;
font-size: 28rpx;
line-height: 1.6;
color: var(--muted);
text-align: center;
}
.page-retry {
margin-top: 24rpx;
padding: 12rpx 28rpx;
border: 2rpx solid var(--brand-strong);
border-radius: 28rpx;
font-size: 26rpx;
font-weight: 500;
color: var(--brand-strong);
}
/* ===== 通栏白块 =====
白面 + 上下各 2rpx 发丝线 + 中性阴影,圆角 0;
负向 margin 抵消容器 32rpx 内距后左右顶到屏幕两侧,
@@ -31,12 +57,22 @@ page {
/* 行高约 87rpx(28rpx×1.4 + 上下 24rpx),贴近 iOS 44pt 触控目标 */
.form-row {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
padding: 24rpx 32rpx;
border-bottom: 2rpx solid var(--line);
}
.field-error {
width: 100%;
margin-top: 12rpx;
font-size: 24rpx;
line-height: 1.5;
color: #B4231A;
text-align: right;
}
.form-row-last {
border-bottom: none;
}
+32 -45
View File
@@ -1,9 +1,12 @@
const API = require('../../utils/api.js')
const { formatDate } = require('../../utils/date.js')
const { maskIdNumber } = require('../../utils/privacy.js')
Page({
data: {
profiles: [],
loading: false
loading: false,
loadError: ''
},
// 用 onShow 而不是 onLoad:从新增/编辑页返回后需要刷新列表
@@ -17,41 +20,34 @@ Page({
})
},
// 拉取当前登录用户的就诊人列表
loadProfiles() {
this.setData({
loading: true
})
// 拉取当前登录用户的就诊人列表;空数组只在请求成功后展示为空态。
async loadProfiles() {
this.setData({ loading: true, loadError: '' })
return API.healthProfile.getMyProfiles({
page: 1,
pageSize: 50
})
.then((res) => {
if (res.code !== 0) {
wx.showToast({
title: res.msg || '加载失败',
icon: 'none'
})
return
}
const list = (res.data && res.data.list) || []
this.setData({
profiles: list.map((item) => this.formatProfile(item))
})
})
.catch((err) => {
console.log('获取就诊人失败', err)
wx.showToast({
title: '网络请求失败',
icon: 'none'
})
})
.finally(() => {
this.setData({
loading: false
})
try {
await getApp().waitForAuth()
const res = await API.healthProfile.getMyProfiles({ page: 1, pageSize: 50 })
if (res.code !== 0) throw new Error(res.msg || '就诊人加载失败')
const list = (res.data && res.data.list) || []
this.setData({
profiles: list.map((item) => this.formatProfile(item))
})
} catch (err) {
console.log('获取就诊人失败', err)
if (this.data.profiles.length === 0) {
this.setData({ loadError: err.message || '网络请求失败,请重试' })
} else {
// 已有成功数据时保留列表,刷新失败不打断查看和编辑。
wx.showToast({ title: '刷新失败,请重试', icon: 'none' })
}
} finally {
this.setData({ loading: false })
}
},
retryLoad() {
this.loadProfiles()
},
// 后端返回的是嵌套结构,这里拍平成卡片展示需要的字段
@@ -63,13 +59,13 @@ Page({
// 顺序:出生年月 → 联系电话 → 证件号(脱敏)
const metaList = []
if (profile.birth) {
metaList.push(profile.birth)
metaList.push(formatDate(profile.birth, profile.birth))
}
if (profile.mobile) {
metaList.push(profile.mobile)
}
if (profile.idnumber) {
metaList.push(this.maskIdNumber(profile.idnumber))
metaList.push(maskIdNumber(profile.idnumber))
}
return {
@@ -83,15 +79,6 @@ Page({
}
},
// 证件号脱敏:仅保留前 4 位与后 4 位(只在有值时调用)
maskIdNumber(idnumber) {
const value = String(idnumber || '')
if (value.length <= 8) {
return value
}
return `${value.slice(0, 4)}********${value.slice(-4)}`
},
onAdd() {
wx.navigateTo({
url: '/pages/health/profileedit'
+7 -1
View File
@@ -46,8 +46,14 @@
</view>
</view>
<!-- 请求失败与真实空态分开,失败时提供原地重试。 -->
<view class="load-error" wx:if="{{!loading && loadError}}">
<text class="load-error-text">{{loadError}}</text>
<view class="retry-btn" bindtap="retryLoad">重新加载</view>
</view>
<!-- 空状态 -->
<view class="profile-empty" wx:if="{{!loading && profiles.length === 0}}">
<view class="profile-empty" wx:if="{{!loading && !loadError && profiles.length === 0}}">
<t-icon name="user-checked" class="profile-empty-icon" size="80rpx" />
<text class="profile-empty-text">还没有就诊人,添加后下单即可一键带入</text>
</view>
+25
View File
@@ -183,6 +183,31 @@ page {
white-space: nowrap;
}
/* ===== 加载失败 ===== */
.load-error {
display: flex;
flex-direction: column;
align-items: center;
padding: 100rpx 32rpx;
}
.load-error-text {
font-size: 28rpx;
line-height: 1.6;
color: var(--muted);
text-align: center;
}
.retry-btn {
margin-top: 24rpx;
padding: 12rpx 28rpx;
border: 2rpx solid var(--brand-strong);
border-radius: 28rpx;
font-size: 26rpx;
font-weight: 500;
color: var(--brand-strong);
}
/* ===== 空态 ===== */
.profile-empty {
display: flex;