此次功能为添加邮箱校验功能,无需必填,但是录入则需要校验邮箱格式,可动态添加最多支持五条数据。
<el-form
ref="partFiveFormRef"
:model="formData"
style="width: 80%"
label-width="160px"
>
<el-row :gutter="20">
<template v-for="(item, index) of formData.emailList" :key="item.ids">
<el-col :span="8">
<el-form-item
label="Email:"
v-if="model === 'operation'"
:prop="'emailList.' + index + '.email'"
:rules="[
{
validator: checkEmail,
trigger: 'blur'
}
]"
>
<template v-if="model === 'operation'">
<div class="flex items-center">
<el-input
v-model="item.email"
style="width: 200px"
placeholder="Input Email"
/>
<el-icon
class="ml-2 cursor-pointer"
size="20px"
@click="addEmail"
v-if="
formData.emailList.length === index + 1 && index !== 4
"
>
<CirclePlusFilled />
</el-icon>
<el-icon
class="ml-2 cursor-pointer"
size="20px"
@click="removeEmail(item.ids)"
v-if="index !== 0"
color="#ed2828"
>
<DeleteFilled />
</el-icon>
</div>
</template>
<span v-else>{{ item.email }}</span>
</el-form-item>
</el-col>
</template>
</el-row>
<el-button type="primary" @click="handleSubmitPartFiveData">
Primary
</el-button>
</el-form>
邮箱校验:
/* 校验邮箱 */
const checkEmail = (rule, value, callback) => {
const regex =
/^[a-zA-Z0-9]+([._\\-]?[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([._\\-]?[a-zA-Z0-9]+)*\.[a-zA-Z]{2,}$/;
if (value && !regex.test(value))
return callback(new Error("Incorrect email format"));
return callback();
};
核心代码部分:
<template v-for="(item, index) of formData.emailList" :key="item.ids">
<el-col :span="8">
<el-form-item
label="Email:"
v-if="model === 'operation'"
:prop="'emailList.' + index + '.email'"
:rules="[
{
validator: checkEmail,
trigger: 'blur'
}
]"
>
注意:
(1)要使用的扩展列表要用<template>包含 , v-for的key需要自增保持唯一,这里使用了随机数ids使key值唯一
(2):prop="'emailList.' + index + '.email'" 的内容,
emailList是数组的名字
index是v-for的 index 序列号,email是输入框的检验变量 ,注意:一定要和验证字段的参数名字严格对应,比如,上面例子和输入框<el-input @input="$forceUpdate()" v-model="item.email" /> 中的v-model值email严格对应