form表单校验时的类型转换

73 阅读1分钟

前言

后台管理系统中经常存在这样一种情况,输入框内输入的长度是x,而且规定输入框内只能输入数字类型的。注意,基本类型中数字是没有长度的。只有字符串才有length这个属性。

代码演示:

<template>
  <el-form
    ref="formRef"
    style="max-width: 600px"
    :model="numberValidateForm"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item
      label="age"
      prop="age"
      :rules="[
        { required: true, message: 'age is required' },
        { max: 3, message: 'age must be a number' },
      ]"
    >
      <el-input
        v-model.number="numberValidateForm.age"
        type="text"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(formRef)">Submit</el-button>
      <el-button @click="resetForm(formRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

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

const formRef = ref<FormInstance>();

const numberValidateForm = reactive({
  age: "",
});

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

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

console.log(222) 

</script>

效果如下:

image.png

可能存在某种情况下,后端返回给我们的年龄是这样的:

numberValidateForm.age =111

当我们这样去重新校验时:

image.png

当返回的类型为字符串时:

numberValidateForm.age ='111'

image.png