ZBLOG

为了使“关联客户”按钮在身份证输入正确时可以点击,而在输入不正确时禁用,可以通过计算属性或方法来控制按钮的 disabled 属性。下面是如何实现这一功能的示例代码。

我们将使用一个计算属性来判断身份证号是否有效,然后根据这个状态来控制按钮的可点击性。

  1. <template>
  2. <a-form :model="formModal" ref="formRef" label-col="{ span: 4 }" wrapper-col="{ span: 14 }">
  3. <a-row>
  4. <a-col :span="12">
  5. <a-form-item
  6. label="身份证号"
  7. name="ident"
  8. :rules="[
  9. { required: true, message: '身份证号不能为空', trigger: 'blur' },
  10. { pattern: idCardRegex, message: '身份证号格式不正确', trigger: 'blur' }
  11. ]"
  12. >
  13. <a-input
  14. v-model:value="formModal.ident"
  15. placeholder="请输入18位身份证号"
  16. :disabled="isEditing"
  17. maxlength="18"
  18. @input="handleIdCardInput"
  19. />
  20. </a-form-item>
  21. </a-col>
  22. <a-col :span="6" style="padding-left: 10px" v-if="!isCustomerAssociated && modalType === 'add'">
  23. <a-button
  24. class="margin-right-10 button-light-blue"
  25. type="primary"
  26. :disabled="!isIdCardValid || isEditing" <!-- 根据状态禁用按钮 -->
  27. @click="handleAssociateCustomer"
  28. >
  29. 关联客户
  30. </a-button>
  31. </a-col>
  32. </a-row>
  33. <a-row>
  34. <a-col :span="24">
  35. <a-button type="primary" @click="handleSubmit">提交</a-button>
  36. </a-col>
  37. </a-row>
  38. </a-form>
  39. </template>
  40. <script setup>
  41. import { ref, computed } from 'vue';
  42. import { message } from 'ant-design-vue';
  43. const formRef = ref(null);
  44. const isEditing = ref(false);
  45. const isCustomerAssociated = ref(false);
  46. const modalType = ref('add');
  47. const formModal = ref({
  48. ident: '', // 身份证号
  49. });
  50. // 身份证正则表达式
  51. const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$/;
  52. // 判断身份证是否有效的计算属性
  53. const isIdCardValid = computed(() => {
  54. return idCardRegex.test(formModal.value.ident);
  55. });
  56. // 实时校验身份证号输入
  57. const handleIdCardInput = (e) => {
  58. const value = e.target.value;
  59. if (!/^[0-9Xx]*$/.test(value)) {
  60. // 如果输入的字符不符合规则,则移除非法字符
  61. formModal.value.ident = value.replace(/[^0-9Xx]/g, '');
  62. }
  63. };
  64. // 提交表单
  65. const handleSubmit = () => {
  66. formRef.value.validate()
  67. .then(() => {
  68. message.success('提交成功');
  69. // 提交逻辑
  70. })
  71. .catch((error) => {
  72. console.log('校验失败:', error);
  73. });
  74. };
  75. </script>
  76. <style scoped>
  77. .margin-right-10 {
  78. margin-right: 10px;
  79. }
  80. .button-light-blue {
  81. background-color: #1890ff;
  82. color: #fff;
  83. }
  84. </style>

在上面的代码中:

  1. computed 属性:创建了一个 isIdCardValid 的计算属性,该属性返回当前输入的身份证号是否符合正则表达式。
  2. buttondisabled 属性:将“关联客户”按钮的 disabled 属性设置为 !isIdCardValid || isEditing,这样只有当身份证格式合法且不是编辑状态时,按钮才会可用。


    内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=22864

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?