vue3+elementui form 表单里数组里参数验证,以及动态删减验证

135 阅读1分钟

表单里多数组数据多条规则验证参考

<template>

<el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    status-icon
>


<el-form-item :label="$t('notification.notificationWay')" prop="noticeMode">
    <el-checkbox value="phoneMessage" name="type">{{$t('notification.phoneMessage')}}</el-checkbox>
  </el-checkbox-group>
</el-form-item>

// 数组参数

<el-form-item prop="phoneMessage" :label="$t('notification.phoneMessage')">
  <div v-for="(item, index) in ruleForm.phoneMessage" :key="index" style="width: 70%;" class="d-flex mt-2">
    <el-input v-model="ruleForm.phoneMessage[index]" :placeholder="$t('notification.phoneMessage')" />
    <el-button type="danger" @click="removePhone(index)" style="margin-left: 10px;">{{$t('alarm.delete')}}</el-button>
  </div>
  <el-button v-if="ruleForm.phoneMessage && ruleForm.phoneMessage.length <= 2" type="primary" @click="addPhone" style="margin-left: 10px;" class="mt-2">{{$t('alarm.add')}}</el-button>
</el-form-item>


</el-form>


</template>

<script setup>

const ruleForm = ref({
    noticeMode: [],
    phoneMessage:[]
})

const rules = reactive({
  phoneMessage: [
    {required: true, message: t('notification.phoneMessage'), trigger: 'blur'},
    { validator: validatePhoneMessage, trigger: ['blur', 'change'] }  ]
})


const validatePhoneMessage = (rule, value, callback) => {
  if (!value || value.length === 0) {
    return callback(new Error(t('notification.phoneMessage')))
  }

  const phoneMessagePattern = /^+?[1-9]\d{1,14}$/
  for (let i = 0; i < value.length; i++) {
    console.log(' = value = ', value)
    const phone = value[i]
    if (!phoneMessagePattern.test(phone)) {
      return callback(new Error(t('notification.phoneMessage')))
    }
  }
  callback()
}



// 方法:更新验证规则
const updateRules = () => {

  rules.phoneMessage = [];

  if (ruleForm.value.noticeMode.includes('phoneMessage')) {
    rules.phoneMessage = [
      { required: true, message: t('notification.phoneMessage'), trigger: 'blur' },
      { validator: validatePhoneMessage, trigger: ['blur', 'change'] }
    ];
  }
}

// 当 check 数组变化时,重新调用 updateRules 更新 rules
watch(() => ruleForm.value.noticeMode, updateRules, { deep: true });



</script>