Skip to content

表单校验

规则

利用 Vue 语言特性,在不使用任何三方库地情况下,优雅地对表单进行校验。

示例

👉 在线体验

js
import { reactive } from 'vue'

// 表单数据
const form = reactive({
  name: '',
  email: '',
  password: '',
})

// 错误信息
const errors = reactive({
  name: null,
  email: null,
  password: null,
})

// 校验规则
const rules = {
  name: [value => !!value || '姓名不能为空'],
  email: [
    value => !!value || '邮箱不能为空',
    value =>
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
        value,
      ) || '邮箱格式不正确',
  ],
  password: [value => !!value || '密码不能为空', value => value.length >= 6 || '密码长度必须大于等于6个字符'],
}

// 单字段校验
const validateField = field => {
  const error = rules[field].map(rule => rule(form[field])).find(result => result !== true)
  errors[field] = error || null
}

// 全表单校验
const validateForm = () => {
  let isValid = true
  Object.keys(form).forEach(field => {
    validateField(field)
    if (errors[field]) isValid = false
  })
  return isValid
}

// 提交处理
const handleSubmit = () => {
  if (validateForm()) {
    alert('表单提交成功!')
    console.log('表单数据:', form)
  }
}
template
<form @submit.prevent="handleSubmit">
  <div class="form-item">
    <label for="name">姓名</label>
    <input id="name" v-model="form.name" @blur="validateField('name')" placeholder="请输入内容" />
    <p v-if="errors.name" class="error-message">{{ errors.name }}</p>
  </div>

  <div class="form-item">
    <label for="name">邮箱</label>
    <input id="name" v-model="form.email" @blur="validateField('email')" placeholder="请输入内容" />
    <p v-if="errors.email" class="error-message">{{ errors.email }}</p>
  </div>

  <div class="form-item">
    <label for="name">密码</label>
    <input id="name" v-model="form.password" @blur="validateField('password')" placeholder="请输入内容" />
    <p v-if="errors.password" class="error-message">{{ errors.password }}</p>
  </div>

  <div class="form-item">
    <button type="submit">提交</button>
  </div>
</form>
css
.form-item {
  margin-bottom: 1rem;
}
.error-message {
  color: red;
  font-size: 0.75rem;
  margin-top: 0.25rem;
}

基于 MIT 许可发布