【ts+vant】身份证号校验和性别验证

校验规则

const nameRules = [
  { required: true, message: '请输入姓名' },
  { pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/, message: '中文2-16个字符' }
]

const idCardRules = [
  { required: true, message: '请输入身份证号' },
  {
    pattern:
      /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
    message: '身份证号不正确'
  }
]

export {   nameRules, idCardRules }

 <!-- 表单 -->
      <van-form ref="form">
        <van-field
          :rules="idCardRules"  校验规则
          v-model="patient.idCard"
          label="身份证号"
          placeholder="请输入身份证号"
        />
        <van-field label="性别" class="pb4">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn
              v-model:gender="patient.gender"
              :options="options"
            ></cp-radio-btn>
          </template>
        </van-field>
      </van-form>
import { nameRules, idCardRules } from '@/utils/rules'
import { showConfirmDialog, type FormInstance } from 'vant'

// 5.点击保存表单
const form = ref<FormInstance>()//获取表单dom
const submit = async () => {
  // 整体校验
  await form.value?.validate()
  //  校验通过
  // 性别需要和身份证包含性别填写的一致,确认框提示
  // 身份证倒数第二位,单数是男,双数是女
  // slice已有数组中返回选定的元素,返回一个新数组,包含从start到end(不包含该元素)的数组元素。(不会改变原数组)
  const gender = +patient.value.idCard.slice(-2, -1) % 2
  if (gender !== patient.value.gender) {
    await showConfirmDialog({
      title: '温馨提示',
      message: '填写的性别和身份证号中的不一致\n您确认提交吗?'
    })
  }
  console.log('通过校验')
}

猜你喜欢

转载自blog.csdn.net/weixin_51290060/article/details/130027503
今日推荐