(el-Form) operation (not using ts): the use of Form form component validation rules in Element-plus

Ⅰ. The comparison between the Element-plusprovided Formform components and the desired target situation:

1. Element-plusProvide Formform components:

First, the Element-plusself-provided Formcode is (sample code):

insert image description here


// Element-plus 自提供的代码:
// 此时是使用了 ts 语言环境,但是我在实际项目中并没有使用 ts 语言和环境;

<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
    <el-form-item label="Password" prop="pass">
      <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item label="Confirm" prop="checkPass">
      <el-input
        v-model="ruleForm.checkPass"
        type="password"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item label="Age" prop="age">
      <el-input v-model.number="ruleForm.age" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >Submit</el-button
      >
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {
    
     reactive, ref } from 'vue'
import type {
    
     FormInstance, FormRules } from 'element-plus'

const ruleFormRef = ref<FormInstance>()

const checkAge = (rule: any, value: any, callback: any) => {
    
    
  if (!value) {
    
    
    return callback(new Error('Please input the age'))
  }
  setTimeout(() => {
    
    
    if (!Number.isInteger(value)) {
    
    
      callback(new Error('Please input digits'))
    } else {
    
    
      if (value < 18) {
    
    
        callback(new Error('Age must be greater than 18'))
      } else {
    
    
        callback()
      }
    }
  }, 1000)
}

const validatePass = (rule: any, value: any, callback: any) => {
    
    
  if (value === '') {
    
    
    callback(new Error('Please input the password'))
  } else {
    
    
    if (ruleForm.checkPass !== '') {
    
    
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
    
    
  if (value === '') {
    
    
    callback(new Error('Please input the password again'))
  } else if (value !== ruleForm.pass) {
    
    
    callback(new Error("Two inputs don't match!"))
  } else {
    
    
    callback()
  }
}

const ruleForm = reactive({
    
    
  pass: '',
  checkPass: '',
  age: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
    
    
  pass: [{
    
     validator: validatePass, trigger: 'blur' }],
  checkPass: [{
    
     validator: validatePass2, trigger: 'blur' }],
  age: [{
    
     validator: checkAge, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
    
    
  if (!formEl) return
  formEl.validate((valid) => {
    
    
    if (valid) {
    
    
      console.log('submit!')
    } else {
    
    
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
    
    
  if (!formEl) return
  formEl.resetFields()
}
</script>


Code address ( 直接点击下面 url 跳转): https://element-plus.gitee.io/zh-CN/component/form.html#Custom validation rules

Second, the display of the page is as follows:

insert image description here

2. The situation after the target wants to be modified:

// At this time, although the style of the page has changed, the actual form syntax or validation rules have not changed;

insert image description here

Ⅱ. Realize Formthe process of changing the form component to achieve the target effect:

1. The process of Formsuccessfully introducing the form component into vue3the project ( tsthe grammar of is removed):

First, the code (taking age as an example):

<script setup>

import {
    
    ref} from 'vue'

const ruleFormRef = ref(null)   // 注意:一定要定义 form 表单中 ref 的 ruleFormRef 的值,否则会一直报错;

const ruleForm = ref({
    
    
  pass: "",
  checkPass: "",
  age: '',
  // size: '4000',
  // ip: '0.0.0.0'
})


// 重置的操作;
const resetForm = (val) => {
    
    
  debugger
  if (!val) return
  val.resetFields()  // resetFields 函数:是将表单字段的值重置为其默认值;
}


// age 的规则是:让 age 的值,不能为空,为数字,且数字值不小于 18;
const checkAge = (rule, value, callback) => {
    
    
  if (!value) {
    
      // 此时是判空,如果 age 中为空,就抛出该提示信息;
    return callback(new Error('Please input the age'))
  }
  setTimeout(() => {
    
    
    if (!Number.isInteger(value)) {
    
       // 此时是:判断 age 中输入的值是否是数字,如果不是数字就抛出该提示信息;
      callback(new Error('Please input digits'))
    } else {
    
    
      if (value < 18) {
    
     // 此时是:判断 age 中输入的数字是否小于 18,如果小于 18,就抛出该提示信息;
        callback(new Error('Age must be greater than 18'))
      } else {
    
    
        callback()
      }
    }
  }, 1000)
}


// 注意:在 rules 方法中 validator 属性后面的方法,一定要定义在 rules 函数前,否则会报错;
const rules = ref({
    
    
  age: [
    {
    
     validator: checkAge, trigger: 'blur' }
  ],
})


// 此时是:提交表单的操作;
const submitForm = () => {
    
    
  if (!ruleFormRef.value) return
  ruleFormRef.value.validate((valid) => {
    
      // 注意:此时使用的是 ruleFormRef.value,而仅写 ruleFormRef 是拿不到值且会报错的;
    if (valid) {
    
       // 注意:只有当所有的规则都满足后,此时的 valid 的值才为 true,才能执行下面的值;
      console.log('submit!')
    } else {
    
    
      console.log('error submit!')
      return false
    }
  })
}

</script>

<template>
  <div class="project_background">
    <div class="my_project">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="Password" prop="pass">
          <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="Confirm" prop="checkPass">
          <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="Age" prop="age">
          <el-input v-model.number="ruleForm.age" />
        </el-form-item>
        <!-- <el-form-item label="大小" prop="log_size">
          <el-tooltip class="box-item" effect="light" content="请填写 500 到 4000 的数" placement="top">
            <el-input v-model="ruleForm.size" placeholder="请输入"/>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="IP" prop="log_service_ip">
          <el-tooltip class="box-item" effect="light" content="请填写合法的 ip 地址" placement="top">
            <el-input v-model="ruleForm.ip" placeholder="请输入"/>
          </el-tooltip>
        </el-form-item>  -->
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"><el-icon :size="20" style="margin-right: 5px;"><CircleCheckFilled /></el-icon>Submit</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
 .project_background {
    
    
  margin: 30px auto;
  background-color: #e6f1f9;
  box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 40px 0px;
  .my_project {
    
    
    margin: 20px;
  }
 }
</style>

Second, the effect display:

A. If the input value is not a number, an error will be reported:

insert image description here
B. If the input value is less than 18, an error will also be reported:

insert image description here
C. Only the correct value can be submitted successfully:

insert image description here

Ⅲ. Modify Formthe display of the form component to achieve the target effect:

1. The overall code (ie: total code):


// 此时是去除 ts 的 Element-plus 组件的 vue3 语法的代码:

<script setup>

import {
    
    ref} from 'vue'

const ruleFormRef = ref(null)   // 注意:一定要定义 form 表单中 ref 的 ruleFormRef 的值,否则会一直报错;

const ruleForm = ref({
    
    
  pass: "",
  checkPass: "",
  age: ''
})


// 重置的操作;
const resetForm = (val) => {
    
    
  debugger
  if (!val) return
  val.resetFields()  // resetFields 函数:是将表单字段的值重置为其默认值;
}


// Password 的规则是:让 Password 的输入值,不能为空,且若 Confirm 的输入值不为空时,在 Password 的输入值后在执行一遍 Confirm 的规则;
const validatePass = (rule, value, callback) => {
    
    
  if (value === '') {
    
      // 此时是判空,如果 Password 中为空,就抛出该提示信息;
    callback(new Error('Please input the password'))
  } else {
    
    
    if (ruleForm.value.checkPass !== '') {
    
      // 此时是:判断 Confirm 输入的值是否为空;
      if (!ruleFormRef.value) return  // 只要 Confirm 中有输入,此时的 !ruleFormRef.value 的布尔值为 false;
      ruleFormRef.value.validateField('checkPass', () => null) // validateField 是用于对表单中的字段进行验证的方法,来确保数据的正确性;
                                                               // 个人理解是:在 Confirm 中有输入与 Password 的输入对比的操作,因此可以理解为:对 'checkPass'(即:Confirm)
                                                               // 进行监听,即:有执行了一遍 Confirm 的验证(确定:通过 debugger 验证了猜想);
    }
    callback()
  }
}

// Confirm 的规则是:让 Confirm 的输入值,不能为空,且与 Password 的输入值要保持一致;
const validatePass2 = (rule, value, callback) => {
    
    
  if (value === '') {
    
      // 此时是判空,如果 Confirm 中为空,就抛出该提示信息;
    callback(new Error('Please input the password again'))
  } else if (value !== ruleForm.value.pass) {
    
     // 此时是:判断 Confirm 输入的值是否与 Password 输入的值相同,若不相同,就抛出该提示信息;
    callback(new Error("Two inputs don't match!"))
  } else {
    
     // 只有 Confirm 输入的值与 Password 输入的值相同,才没问题(前提是:Passwork 与 Confirm 中都有值);
    callback()
  }
}


// age 的规则是:让 age 的值,不能为空,为数字,且数字值不小于 18;
const checkAge = (rule, value, callback) => {
    
    
  if (!value) {
    
      // 此时是判空,如果 age 中为空,就抛出该提示信息;
    return callback(new Error('Please input the age'))
  }
  setTimeout(() => {
    
    
    if (!Number.isInteger(value)) {
    
       // 此时是:判断 age 中输入的值是否是数字,如果不是数字就抛出该提示信息;
      callback(new Error('Please input digits'))
    } else {
    
    
      if (value < 18) {
    
     // 此时是:判断 age 中输入的数字是否小于 18,如果小于 18,就抛出该提示信息;
        callback(new Error('Age must be greater than 18'))
      } else {
    
    
        callback()
      }
    }
  }, 1000)
}


// 注意:在 rules 方法中 validator 属性后面的方法,一定要定义在 rules 函数前,否则会报错;
const rules = ref({
    
    
  // form 表单前面有没有小红星,取决于有没有 'required: true' 的属性,如果有这个属性页面就有小红星,而没有这个属性就没有小红星;
  pass: [
    {
    
     required: true, validator: validatePass, trigger: 'blur' }
  ],
  checkPass: [
    {
    
     validator: validatePass2, trigger: 'blur' }
  ],
  age: [
    {
    
     validator: checkAge, trigger: 'blur' }
  ],
})


// 此时是:提交表单的操作;
const submitForm = () => {
    
    
  if (!ruleFormRef.value) return
  ruleFormRef.value.validate((valid) => {
    
      // 注意:此时使用的是 ruleFormRef.value,而仅写 ruleFormRef 是拿不到值且会报错的;
    if (valid) {
    
       // 注意:只有当所有的规则都满足后,此时的 valid 的值才为 true,才能执行下面的值;
      console.log('submit!')
    } else {
    
    
      console.log('error submit!')
      return false
    }
  })
}

</script>

<template>
  <div class="project_background">
    <div class="my_project">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="Password" prop="pass">
          <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="Confirm" prop="checkPass">
          <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="Age" prop="age">
          <el-input v-model.number="ruleForm.age" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"><el-icon :size="20" style="margin-right: 5px;"><CircleCheckFilled /></el-icon>Submit</el-button
          >
          <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
 .project_background {
    
    
  margin: 30px auto;
  background-color: #e6f1f9;
  box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 40px 0px;
  .my_project {
    
    
    margin: 20px;
  }
 }
</style>


2. Display of the overall effect:

insert image description here

Ⅳ. Summary:

First, where there is something wrong or inappropriate, please give me some pointers and exchanges!
Second, if you repost or quote the content of this article, please indicate the address of this blog ( 直接点击下面 url 跳转) https://blog.csdn.net/weixin_43405300 , creation is not easy, but it can be done and cherished!
Third, if you are interested, you can pay more attention to this column (Vue (Vue2+Vue3) interview must-have column) ( 直接点击下面 url 跳转): https://blog.csdn.net/weixin_43405300/category_11525646.html?spm=1001.2014.3001.5482

Guess you like

Origin blog.csdn.net/weixin_43405300/article/details/132224475