Skip to content

表单校验我们可以将复杂的校验逻辑单独提取出来,src/views/login/rules.js

javascript
export const validatePassword = () => {
  return (rule, value, callback) => {
    if (value.length < 6) {
      callback(new Error('密码不能少于6位'))
    } else {
      callback()
    }
  }
}

表单需要绑定元素和校验规则

vue
<template>
  <div class="login-container">
    <el-form class="login-form" ref="loginFormRef" :model="loginForm" :rules="loginRules">
      <el-form-item prop="username">
        <el-input placeholder="请输入您的账号" v-model="loginForm.username" name="username" type="text"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input placeholder="请输入您的密码" v-model="loginForm.password" name="password" type="password"></el-input>
      </el-form-item>
      <el-button size="large" type="primary" @click="submitForm(loginFormRef)">登录</el-button>
    </el-form>
  </div>
</template>
<script setup>
import { reactive, ref } from "vue"
import { validatePassword } from "@/views/login/rules"

const loginForm = reactive({
  username: "",
  password: ""
})
const loginFormRef = ref()
const loginRules = ref({
  username: [
    {
      required: true,
      trigger: 'blur',
      message: '用户名为必填项'
    }
  ],
  password: [
    {
      required: true,
      trigger: 'blur',
      validator: validatePassword()
    }
  ]
})

// 点击登录,先对表单进行校验
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('校验通过!')
    } else {
      console.log('校验不通过!', fields)
    }
  })
}
</script>