(ElementPlus) operation (without ts): Form form inspection, rules and case analysis (this one is enough)

Ⅰ. FormIntroduction to form inspection:

1. What is Formform inspection?

One, attributes:

Form validation is javascriptone of the advanced options in ;

Second, the definition:

JavaScriptThe behavior of validating these input data in before the data is sent to the server is called form HTMLvalidation ;Form 表单

2. Why use Formform check (meaning)?

First, the front-end pre-verification can save some wrong request submissions, and save interface pressure for the back-end (ie: reduce the pressure on the server);

Second, ensure that the input data meets the requirements to facilitate data interaction;

Third, ensure the feasibility of the data (that is: the data meets the requirements) and security;

Ⅱ. FormAttributes and parameters of form validation:

1. The basic flow of form verification:

First, declare the form object:ref="ruleFormRef"

A. Form object:

At this time, ruleFormRef is the form object of el-form. The properties of the declared form object are generally consistent with the fields required by the interface, which is more convenient and trouble-free when transferring data;

B. Precautions: Be sure to declare;

insert image description here

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

Second, the form data object::model="ruleForm"

A. First use refto declare (at this time ruleFormwill have a responsive):

insert image description here

B. The value bound in el-form-item must be the value defined in ruleForm;

// That is: the value bound by v-model="ruleForm.passWord" in el-input at this time is defined in ruleForm;

insert image description here

Third, form validation rules::rules="rules"

A. The rules defined in rules are the verification rules, which generally use attributes and parameters:

insert image description here

B. The rules defined in rules are the verification rules, and it is also possible to use a custom verification function:

// The custom function refers to: validator: validatePass, and the validatePass function is a function to verify the passWord attribute (ie: custom verification rules);

insert image description here

insert image description here

2. Form properties and parameters:

First, the commonly used attributes:

Attributes attribute meaning attribute value
required Is it required? true / false
message Message prompt for failed verification string type, custom
trigger How the validation logic is triggered blue (triggered when focus is lost) / change (triggered when the corresponding data changes)
pattern Regular expression to validate data A regular expression that satisfies the requirement
type type of validation data array, string, data, string, numer, email …
min Minimum length of input number type, custom
max the maximum length of the input number type, custom
validator custom validation rules It is a function and has three parameters: rule [current verification rule]; value [data in the input box]; callback [callback function, which must be executed regardless of whether it passes the verification. When the verification fails, a prompt message will be displayed: callback (new Error('prompt message'))]

Second, the situation that needs attention:

A, 规则对象的属性and 表单数据对象的属性must be consistent:

// At this time, it means: rules 中的属性值and ruleForm 中的属性值must be consistent (take checkPassWord as an example);

insert image description here
insert image description here

B. Must be on el-item-form prop="表格属性值"to trigger the verification work:

insert image description here

C. The attribute value of the attribute of the rule object is Array, which means that multiple verification rules can be bound (not understood yet);

D. When customizing the verification rules, the callback() function must be executed regardless of whether the verification is passed;

// The validatePass function at this time is a custom validation function, which will be executed regardless of whether it passes the validation (that is, the callback() function will be executed eventually);

insert image description here

3. The actual usage of Form form attributes:

First, usage of required, message, trigger attributes:

A. At this time, when required is true, there is insert image description herea mark in front of the verification form (indicating that it is required), message is the information to be prompted when the input is empty, and trigger refers to the trigger method (blur means: lose focus);

insert image description here

B. The code is:


<script setup>

import {
    
    ref} from 'vue'

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

const ruleForm = ref({
    
    
  name: '',
})


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

const rules = ref({
    
    
  name: [
    {
    
     required: true, message: 'name 不能为空', 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="100px"
        class="demo-ruleForm"
      > 
        <el-form-item label="name:" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入"/>
        </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>

C. The page with empty input is displayed as:

insert image description here

Second, the usage of min and max attributes:

A. min refers to: the minimum length of input, max refers to: the maximum length of input;

insert image description here

B. The code is:

<script setup>

import {
    
    ref} from 'vue'

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

const ruleForm = ref({
    
    
  name: '',
})


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

const rules = ref({
    
    
  name: [
    {
    
     required: true, message: 'name 不能为空', trigger: 'blur' },       // 此时是防空判断;
    {
    
     min: 7, max: 11, message: '长度在 7 到 11 个字符', trigger: 'blur' }  // 此时是:判断输入值是否是 7~11 位(即:name 的校验规则);
  ],
})


// 此时是:提交表单的操作;
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="100px"
        class="demo-ruleForm"
      > 
        <el-form-item label="name:" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入"/>
        </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>

C. The page for entering the required length is displayed as:

insert image description here

insert image description here

Third, the usage of the type attribute:

A. type refers to: the type of input data;

insert image description here

B. The code is:


<script setup>

import {
    
    ref} from 'vue'

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

const ruleForm = ref({
    
    
  email: '',
})


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

const rules = ref({
    
    
   email: [
     {
    
     required: true, message: 'email 不能为空', trigger: 'blur' },    // 此时是防空判断;
     {
    
     type: "email",  message: "请输入正确的邮箱",  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="100px"
        class="demo-ruleForm"
      > 
        <el-form-item label="邮箱地址:" prop="email">
          <el-input v-model="ruleForm.email" placeholder="请输入"/>
        </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>

C. The page for entering the required type is displayed as follows:

insert image description here

insert image description here

Fourth, the usage of the pattern attribute:

A. pattern refers to: the regular expression of the input data;

insert image description here

B. The code is:


<script setup>

import {
    
    ref} from 'vue'

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

const ruleForm = ref({
    
    
  phone: '',
})


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

const rules = ref({
    
    
    phone: [
     {
    
     required: true, message: 'phone 不能为空', trigger: 'blur' },    // 此时是防空判断;
     {
    
     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的电话", 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="100px"
        class="demo-ruleForm"
      > 
        <el-form-item label="手机号:" prop="phone">    <!-- 注意:一定要在 el-form-item 上添加 prop 值的绑定,否则不会触发校验; -->
          <el-input v-model="ruleForm.phone" placeholder="请输入"/>
        </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>

C. The page displaying the required regular expression is as follows:

insert image description here

insert image description here

Fifth, the usage of the validator attribute:

A. validator refers to: the function of custom validation rules;

insert image description here
insert image description here

B. The code is:


<script setup>

import {
    
    ref} from 'vue'

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

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


// 重置的操作;
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)
}

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="100px"
        class="demo-ruleForm"
      > 
        <el-form-item label="Age:" prop="age">
          <el-input v-model.number="ruleForm.age" placeholder="请输入" autocomplete="off"/>
          <!-- 此时的 v-model.number 已经将校验的 value 值变成数字,而不再是字符串;  若没有 '.number' 这个属性值,那么校验的 value 值将是字符串; -->
        </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>

C. The page display of custom verification rules is as follows:

insert image description here

insert image description here

insert image description here

4. The above-mentioned code and target effect:

First, the overall code is:


// 此时是去除 ts 的 Form 表单校验规则的 vue3 语法的代码:

<script setup>

import {
    
    ref} from 'vue'

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

const ruleForm = ref({
    
    
  passWord: "",
  checkPassWord: "",
  age: '',
  name: '',
  ip: '',
  email: '',
  phone: ''
})


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


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

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

// phone 的规则是:让 phone 的值,不能为空,为数字,且符合手机号的校验规则;
const validatePhone = (rule, value, callback) => {
    
    
  if (!value) {
    
      // 此时是判空,如果 phone 中为空,就抛出该提示信息;
    return callback(new Error('Please input the phone number'))
  } 
  setTimeout(() => {
    
    
    if(!Number.isInteger(Number(value))) {
    
     // 此时是:判断 phone 中输入的值是否是数字,如果不是数字就抛出该提示信息;
                                           // 此时:虽然 value 的值是一个字符串,但是当输入的是数字时,通过 Number(value) 操作此时已经变成了数字, 然后再进行 Number.isInteger() 的判断;
      callback(new Error('Please input digits')) 
    } else {
    
    
      if(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value)) {
    
     // 此时是:判断 phone 中输入的数字是否符合手机号的校验规则,如果不符合就抛出提示信息;
        callback()
      } else {
    
    
        callback(new Error('Please input the valid phone number'))
      }
    }
  })
}

// 可能存在的判断是否有重复手机号的校验(即:根据后台的返回值来判断):
// const checkTelCode = async (rule, value, callback) => {
    
    
//   if (value) {
    
    
//     await validPhoneUnique({ phonenumber: value }).then((response) => {
    
    
//       if (response.code == 200) {
    
    
//         callback();
//       } else {
    
    
//         callback(new Error("手机号已存在"));
//       }
//     });
//   }
// }

// 注意:在 rules 方法中 validator 属性后面的方法,一定要定义在 rules 函数前,否则会报错;
const rules = ref({
    
    
  // form 表单前面有没有小红星,取决于有没有 'required: true' 的属性,如果有这个属性页面就有小红星,而没有这个属性就没有小红星;
  passWord: [
    {
    
     required: true, validator: validatePass, trigger: 'blur' }
  ],
  checkPassWord: [
    {
    
     validator: validatePass2, trigger: 'blur' }
  ],
  age: [
    {
    
     validator: checkAge, trigger: 'blur' }
  ],
  name: [
    {
    
     required: true, message: 'name 不能为空', trigger: 'blur' },       // 此时是防空判断;
    {
    
     min: 7, max: 11, message: '长度在 7 到 11 个字符', trigger: 'blur' }  // 此时是:判断输入值是否是 7~11 位(即:name 的校验规则);
  ],
  ip: [
    {
    
     required: true, message: 'IP不能为空', trigger: 'blur' },
    {
    
     pattern: /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/, message: "请填写合法的IP地址", trigger: "blur"}
    // 此时的 pattern 是合法 ip 地址的正则表达式,当失去焦点后,就会触发正则表达式的判断, 若不满足正则表达式的条件就会提示 message 中的信息;
  ],
  email: [
    {
    
     required: true, message: 'email 不能为空', trigger: 'blur' },    // 此时是防空判断;
    {
    
     type: "email",  message: "请输入正确的邮箱",  trigger: "blur"  }   // 此时是:判断是否是正确邮箱格式(即:邮箱的校验规则);
  ],
  phone: [
    {
    
     required: true, validator: validatePhone, trigger: 'blur' },    // 此时是防空判断;
    // { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的电话", 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="100px"
        class="demo-ruleForm"
      >  <!-- 此时的 status-icon 属性是决定在框里右侧的图标的(符合规则的图标或不符合规则的图标) -->
        <el-form-item label="Password:" prop="passWord">
          <el-input v-model="ruleForm.passWord" type="password" placeholder="请输入" autocomplete="off" />
        </el-form-item>
        <el-form-item label="checkPassWord:" prop="checkPassWord">
          <el-input v-model="ruleForm.checkPassWord" type="password" placeholder="请输入" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="Age:" prop="age">
          <el-input v-model.number="ruleForm.age" placeholder="请输入" autocomplete="off"/>
          <!-- 此时的 v-model.number 已经将校验的 value 值变成数字,而不再是字符串;  若没有 '.number' 这个属性值,那么校验的 value 值将是字符串; -->
        </el-form-item>
        <el-form-item label="name:" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入"/>
        </el-form-item> 
        <el-form-item label="IP地址:" prop="ip">
          <el-input v-model="ruleForm.ip" placeholder="请输入"/>
        </el-form-item> 
        <el-form-item label="邮箱地址:" prop="email">
          <el-input v-model="ruleForm.email" placeholder="请输入"/>
        </el-form-item> 
        <el-form-item label="手机号:" prop="phone">  <!-- 注意:一定要在 el-form-item 上添加 prop 值的绑定,否则不会触发校验; -->
          <el-input v-model="ruleForm.phone" placeholder="请输入"/>
        </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 page display is:

// all empty cases;

insert image description here

// The case where none of the tests are satisfied;

insert image description here

// The situation that all satisfies the test;

insert image description here

Ⅲ. FormActual cases of form validation:

1. The code is:


// 此时是去除 ts 的 Form 表单校验规则的 vue3 语法的代码:

<script setup>

    import {
    
     ElMessage } from 'element-plus'
    import {
    
     ref, reactive } from 'vue'

    const loginFormRef = ref(null);

    // 表单对象
    const loginForm = reactive({
    
    
        username: '',
        password: '',
        agree: true
    });



    // 规则对象
    /**
     * 自定义校验函数 - 参数介绍
     * @param { any } rule 当前对应的规则
     * @param { any } value 对应文本框的值
     * @param { any } callback 回调函数,不管是否通过校验,都必须执行
    */


    const validatorUsername = (rule, value, callback) => {
    
    
        if (!/^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/.test(value)) return callback(new Error("请输入正确格式的手机号!"));
        callback();
    };


    const validatorPwd = (rule, value, callback) => {
    
    
        // 检验密码强度
        if (/\d/.test(value) && /[a-z]/.test(value) && /[A-Z]/.test(value)) return callback();
        callback( new Error("密码强度较弱,请输入带有 大写字母、小写字母、数字三种字符组合的密码!"));
    };

    
    const formRules = {
    
    
        username: [
            // required - 是否必填
            // message - 校验不通过的提示信息
            // trigger - 校验的触发方式【blur - 失去焦点触发;change - v-model绑定的值改变触发】
            {
    
     required: true, message: '用户名不能为空', trigger: 'blur' },

            // validator - 自定义校验规则
            {
    
     validator: validatorUsername, trigger: 'blur' }
        ],
        password: [
            {
    
     required: true, message: '密码不能为空', trigger: 'blur' },

            // min - 最小长度
            // max - 最大长度
            {
    
     min: 6, max: 14, message: '密码长度为 6~14 个字符', trigger: 'blur' },
            {
    
     validator: validatorPwd, triger: 'blur' }
        ],
        agree: [
            // 自定义校验规则
            {
    
    
              validator: (rule, value, callback) => {
    
    
                  if (!value) return callback(new Error('请勾选同意协议!'));
                  callback();
              },
              trigger: 'change'
            }
        ]
    };
    

    // TODO 表单整体校验 + 登录
    const login = () => {
    
    
      loginFormRef.value.validate((valid) => {
    
    
            // 不通过校验
            if (!valid) return ElMessage.error('请填写 登录信息 或 同意协议 再进行登录操作!');
            // 通过校验
            // 登录逻辑
        });
    };
</script>

<template>
    <el-form :model="loginForm" :rules="formRules" ref="loginFormRef" label-position="right" label-width="60px" status-icon>
        <el-form-item label="账户" prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
            <el-input v-model="loginForm.password" placeholder="请输入密码"/>
        </el-form-item>
        
        <el-form-item label-width="22px" prop="agree">
            <el-checkbox size="large" v-model="loginForm.agree">
                我已同意隐私条款和服务条款
            </el-checkbox>
        </el-form-item>
        
        <el-button size="large" class="subBtn" @click="login(loginFormRef)">点击登录</el-button>
    </el-form>
</template>


2. The page is displayed as:

// open the page;
insert image description here

// Prompt when reporting an error:

insert image description here

// Error reporting for unchecked clauses:

insert image description here

// page on success:

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/132326466