为了使“关联客户”按钮在身份证输入正确时可以点击,而在输入不正确时禁用,可以通过计算属性或方法来控制按钮的 disabled
属性。下面是如何实现这一功能的示例代码。
我们将使用一个计算属性来判断身份证号是否有效,然后根据这个状态来控制按钮的可点击性。
<template>
<a-form :model="formModal" ref="formRef" label-col="{ span: 4 }" wrapper-col="{ span: 14 }">
<a-row>
<a-col :span="12">
<a-form-item
label="身份证号"
name="ident"
:rules="[
{ required: true, message: '身份证号不能为空', trigger: 'blur' },
{ pattern: idCardRegex, message: '身份证号格式不正确', trigger: 'blur' }
]"
>
<a-input
v-model:value="formModal.ident"
placeholder="请输入18位身份证号"
:disabled="isEditing"
maxlength="18"
@input="handleIdCardInput"
/>
</a-form-item>
</a-col>
<a-col :span="6" style="padding-left: 10px" v-if="!isCustomerAssociated && modalType === 'add'">
<a-button
class="margin-right-10 button-light-blue"
type="primary"
:disabled="!isIdCardValid || isEditing" <!-- 根据状态禁用按钮 -->
@click="handleAssociateCustomer"
>
关联客户
</a-button>
</a-col>
</a-row>
<a-row>
<a-col :span="24">
<a-button type="primary" @click="handleSubmit">提交</a-button>
</a-col>
</a-row>
</a-form>
</template>
<script setup>
import { ref, computed } from 'vue';
import { message } from 'ant-design-vue';
const formRef = ref(null);
const isEditing = ref(false);
const isCustomerAssociated = ref(false);
const modalType = ref('add');
const formModal = ref({
ident: '', // 身份证号
});
// 身份证正则表达式
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)$/;
// 判断身份证是否有效的计算属性
const isIdCardValid = computed(() => {
return idCardRegex.test(formModal.value.ident);
});
// 实时校验身份证号输入
const handleIdCardInput = (e) => {
const value = e.target.value;
if (!/^[0-9Xx]*$/.test(value)) {
// 如果输入的字符不符合规则,则移除非法字符
formModal.value.ident = value.replace(/[^0-9Xx]/g, '');
}
};
// 提交表单
const handleSubmit = () => {
formRef.value.validate()
.then(() => {
message.success('提交成功');
// 提交逻辑
})
.catch((error) => {
console.log('校验失败:', error);
});
};
</script>
<style scoped>
.margin-right-10 {
margin-right: 10px;
}
.button-light-blue {
background-color: #1890ff;
color: #fff;
}
</style>
在上面的代码中:
computed
属性:创建了一个isIdCardValid
的计算属性,该属性返回当前输入的身份证号是否符合正则表达式。button
的disabled
属性:将“关联客户”按钮的disabled
属性设置为!isIdCardValid || isEditing
,这样只有当身份证格式合法且不是编辑状态时,按钮才会可用。
内容由零声教学AI助手提供,问题来源于学员提问