JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 48
  • Score
    100M100P100Q99110F
  • License MIT

🚀 The most powerful Vue 3 form validation library with 226+ built-in rules

Package Exports

  • @yojack/vue-supervalidator
  • @yojack/vue-supervalidator/dist/index.cjs.js
  • @yojack/vue-supervalidator/dist/index.esm.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@yojack/vue-supervalidator) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Vue Form Validator Plus

一个功能强大、易于使用的 Vue 3 表单校验插件,支持 50+ 种常见校验规则。

✨ 特性

  • 🎯 开箱即用 - 包含 50+ 种内置校验规则
  • 🚀 轻量高效 - 体积小,性能优
  • 💪 TypeScript - 完整的类型定义
  • 🔄 异步校验 - 支持异步校验器
  • 🎨 灵活扩展 - 支持自定义校验规则
  • 📱 响应式 - 基于 Vue 3 响应式系统
  • 🌍 国际化 - 支持自定义错误消息

📦 安装

npm install vue-form-validator-plus

或使用 yarn:

yarn add vue-form-validator-plus

或使用 pnpm:

pnpm add vue-form-validator-plus

🚀 快速开始

全局注册

import { createApp } from 'vue'
import FormValidatorPlugin from 'vue-form-validator-plus'
import App from './App.vue'

const app = createApp(App)

// 注册插件
app.use(FormValidatorPlugin, {
  // 可选:自定义错误消息
  messages: {
    required: '该字段必填',
    email: '邮箱格式不正确'
  }
})

app.mount('#app')

组件中使用

<template>
  <div class="form-container">
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label>用户名:</label>
        <input
          v-model="formData.username"
          @blur="validateField('username')"
          type="text"
        />
        <span class="error" v-if="hasError('username')">
          {{ getFieldError('username') }}
        </span>
      </div>

      <div class="form-group">
        <label>邮箱:</label>
        <input
          v-model="formData.email"
          @blur="validateField('email')"
          type="email"
        />
        <span class="error" v-if="hasError('email')">
          {{ getFieldError('email') }}
        </span>
      </div>

      <div class="form-group">
        <label>手机号:</label>
        <input
          v-model="formData.phone"
          @blur="validateField('phone')"
          type="tel"
        />
        <span class="error" v-if="hasError('phone')">
          {{ getFieldError('phone') }}
        </span>
      </div>

      <div class="form-group">
        <label>密码:</label>
        <input
          v-model="formData.password"
          @blur="validateField('password')"
          type="password"
        />
        <span class="error" v-if="hasError('password')">
          {{ getFieldError('password') }}
        </span>
      </div>

      <div class="form-group">
        <label>确认密码:</label>
        <input
          v-model="formData.confirmPassword"
          @blur="validateField('confirmPassword')"
          type="password"
        />
        <span class="error" v-if="hasError('confirmPassword')">
          {{ getFieldError('confirmPassword') }}
        </span>
      </div>

      <button type="submit" :disabled="validating">
        {{ validating ? '验证中...' : '提交' }}
      </button>
    </form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { useFormValidator } from 'vue-form-validator-plus'

// 表单数据
const formData = reactive({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: ''
})

// 校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名' },
    { minLength: 4, message: '用户名至少4个字符' },
    { maxLength: 16, message: '用户名最多16个字符' },
    { username: true, message: '用户名只能包含字母、数字、下划线' }
  ],
  email: [
    { required: true, message: '请输入邮箱' },
    { email: true, message: '邮箱格式不正确' }
  ],
  phone: [
    { required: true, message: '请输入手机号' },
    { phone: true, message: '手机号格式不正确' }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { minLength: 6, message: '密码至少6个字符' },
    { password: true, message: '密码必须包含数字和字母' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码' },
    { same: 'password', message: '两次密码输入不一致' }
  ]
}

// 创建校验器
const {
  errors,
  validating,
  validate,
  validateField,
  hasError,
  getFieldError,
  clearErrors
} = useFormValidator(formData, rules)

// 提交表单
const handleSubmit = async () => {
  const result = await validate()
  
  if (result.valid) {
    console.log('表单验证通过', formData)
    // 提交表单数据到服务器
  } else {
    console.log('表单验证失败', result.errors)
  }
}
</script>

<style scoped>
.form-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.error {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  display: block;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}
</style>

📚 校验规则

基础校验

规则 类型 说明 示例
required boolean 必填项 { required: true }
min number 最小值 { min: 0 }
max number 最大值 { max: 100 }
minLength number 最小长度 { minLength: 6 }
maxLength number 最大长度 { maxLength: 20 }
length number 固定长度 { length: 11 }
pattern RegExp 正则表达式 { pattern: /^[A-Z]+$/ }

邮箱和通讯

规则 说明 示例
email 邮箱地址 { email: true }
phone 中国手机号 { phone: true }
phoneLoose 宽松的电话号码(含座机) { phoneLoose: true }
tel 座机号码 { tel: true }
mobile 移动电话 { mobile: true }

网络相关

规则 说明 示例
url URL地址 { url: true }
domain 域名 { domain: true }
ip IP地址 { ip: true }
ipv4 IPv4地址 { ipv4: true }
ipv6 IPv6地址 { ipv6: true }
port 端口号(1-65535) { port: true }

数字相关

规则 说明 示例
number 数字 { number: true }
integer 整数 { integer: true }
float 浮点数 { float: true }
positive 正数 { positive: true }
negative 负数 { negative: true }
positiveInteger 正整数 { positiveInteger: true }
negativeInteger 负整数 { negativeInteger: true }

身份证件

规则 说明 示例
idCard 中国身份证号 { idCard: true }
passport 护照号码 { passport: true }

银行和金融

规则 说明 示例
bankCard 银行卡号 { bankCard: true }
creditCard 信用卡号 { creditCard: true }

邮编和地址

规则 说明 示例
zipCode 中国邮政编码 { zipCode: true }
postCode 邮政编码(通用) { postCode: true }

日期和时间

规则 说明 示例
date 日期格式 { date: true }
dateISO ISO日期格式 { dateISO: true }
time 时间格式 { time: true }
dateTime 日期时间 { dateTime: true }

中文相关

规则 说明 示例
chinese 只能是中文 { chinese: true }
chineseAndNumber 中文和数字 { chineseAndNumber: true }
noChinese 不能包含中文 { noChinese: true }

英文和字符

规则 说明 示例
alpha 只能是字母 { alpha: true }
alphaNum 字母和数字 { alphaNum: true }
alphaDash 字母、数字、下划线、破折号 { alphaDash: true }
lowercase 小写字母 { lowercase: true }
uppercase 大写字母 { uppercase: true }

特殊格式

规则 说明 示例
username 用户名格式 { username: true }
password 密码(数字+字母) { password: true }
strongPassword 强密码(数字+字母+特殊字符) { strongPassword: true }
hex 十六进制 { hex: true }
color 颜色值 { color: true }
base64 Base64编码 { base64: true }
md5 MD5格式 { md5: true }
uuid UUID { uuid: true }

车辆相关

规则 说明 示例
licensePlate 车牌号 { licensePlate: true }
vin 车架号 { vin: true }

社交媒体

规则 说明 示例
qq QQ号 { qq: true }
wechat 微信号 { wechat: true }

文件相关

规则 类型 说明 示例
fileExtension string[] 文件扩展名 { fileExtension: ['jpg', 'png'] }
fileSize number 文件大小(字节) { fileSize: 1024000 }
imageFormat boolean 图片格式 { imageFormat: true }

比较验证

规则 类型 说明 示例
same string 与另一字段相同 { same: 'password' }
different string 与另一字段不同 { different: 'oldPassword' }
gt string 大于另一字段 { gt: 'minValue' }
gte string 大于等于另一字段 { gte: 'minValue' }
lt string 小于另一字段 { lt: 'maxValue' }
lte string 小于等于另一字段 { lte: 'maxValue' }

包含验证

规则 类型 说明 示例
in any[] 必须在数组中 { in: ['male', 'female'] }
notIn any[] 不能在数组中 { notIn: ['admin', 'root'] }

自定义验证

// 同步自定义验证
{
  custom: (value, formData) => {
    return value.startsWith('prefix_')
  },
  message: '必须以 prefix_ 开头'
}

// 异步自定义验证
{
  asyncValidator: async (value, formData) => {
    const response = await fetch(`/api/check-username?name=${value}`)
    const data = await response.json()
    return data.available
  },
  message: '用户名已被占用'
}

🔧 API

useFormValidator(formData, rules)

创建表单校验器

参数:

  • formData: 响应式的表单数据对象
  • rules: 校验规则配置

返回:

  • validator: 校验器实例
  • errors: 错误信息对象(响应式)
  • validating: 是否正在校验(响应式)
  • validate(): 校验所有字段
  • validateField(field): 校验单个字段
  • clearErrors(): 清除所有错误
  • clearFieldError(field): 清除指定字段错误
  • reset(): 重置表单
  • setFieldError(field, errors): 设置字段错误
  • getFieldError(field): 获取字段的第一个错误
  • hasError(field): 检查字段是否有错误

🌍 自定义错误消息

全局配置

app.use(FormValidatorPlugin, {
  messages: {
    required: '该字段必填',
    email: '邮箱格式不正确',
    phone: '请输入正确的手机号'
  }
})

单个规则配置

const rules = {
  username: [
    {
      required: true,
      message: '请输入用户名'
    },
    {
      minLength: 4,
      message: '用户名至少需要4个字符'
    }
  ]
}

📝 完整示例

查看 example 目录获取更多示例代码。

📄 License

MIT License © 2024

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📮 联系方式

如有问题或建议,请提交 Issue。