抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

veeValidate 提供了大量验证规则,支持使用 template 标签或者 compositionAPI 编写表单,GitHub 9K star!

安装

# Install with yarn
yarn add vee-validate@next

# Install with npm
npm install vee-validate@next --save

使用

写一个验证邮箱的表单


<script lang="ts" setup>
import { configure, defineRule, Field, Form } from "vee-validate"
import { ref } from "vue";
import { email } from "@vee-validate/rules"
import zh_CN from '@vee-validate/i18n/dist/locale/zh_CN.json'
import { localize } from '@vee-validate/i18n'
// 定义 email 验证规则
defineRule('email', email)
// 配置本地化,错误提示使用中文
configure({
    generateMessage: localize('zh_CN', zh_CN)
})

const username = ref('');
// 在提交并且验证通过后弹窗
const onSubmit = (values: any) => { alert("奥利给!") } 
</script>

<template>
    <div class="container">
        <Form @submit="onSubmit" class="form">
            <h1 class="title">注册</h1>
						<!-- 验证库提供的组件,使用默认插槽自定义样式 -->
          	<Field
                name="email"
                :rules="{ email }"
                label="邮箱"
                #default="{ field, errorMessage }"
            >
                <input
                    type="text"
                    name="email"
                    v-model="username"
                    v-bind="field"
                    placeholder="请输入邮箱"
                />
                <div class="bg-red-300">{{ errorMessage }}</div>
            </Field>
        </Form>
    </div>
</template>

<style class="scss" scoped>
.container {
    @apply w-screen h-screen flex justify-center items-start;
}
.form {
    @apply translate-y-16 h-10;
}
.title {
    @apply text-center mb-14 text-[3rem];
}
input {
    @apply outline-none h-full border-2 border-gray-400 rounded-l-lg  w-96;
}
button {
    @apply bg-blue-500 w-36 h-full outline-none text-white rounded-r-lg;
}
</style>

测试效果

或者还有一种 compositionAPI 写法

Composition API
If you want more fine grained control, you can use useField function to compose validation logic into your component:

import { useField } from 'vee-validate';

export default {
  setup() {
    // Validator function
    const isRequired = value => (value ? true : 'This field is required');
    const { value, errorMessage } = useField('field', isRequired);

    return {
      value,
      errorMessage,
    };
  },
};

Then in your template, use v-model to bind the value to your input and display the errors using errorMessage:

<template>
  <input name="field" v-model="value" />
  <span>{{ errorMessage }}</span>
</template>

仓库地址:

logaretm/vee-validate: ✅ Form Validation for Vue.js (github.com)

评论