vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue3使用vee-validate表单校验,自定义全局验证

Vue3(ts)使用vee-validate表单校验,自定义全局验证规则说明

作者:Summer不秃

这篇文章主要介绍了Vue3(ts)使用vee-validate表单校验,自定义全局验证规则说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

注意:这篇文章代码里的样式引入了tailwindcss

安装并引入

定义全局校验规则 

在utils目录下新建一个validate.ts文件(这里我使用的是ts,如果用js就创建js文件)

内容示例如下: 

import { defineRule } from 'vee-validate';
 
 
defineRule('required', (value: string ) => {
    if (!value || !value.length) {
        return '该字段不能为空';
    }
 
    return true;
});
 
defineRule('email', (value: string ) => {
    if (!value || !value.length) {
        return '邮箱地址不能为空';
    }
    if (!/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/.test(value)) {
        return '请输入有效的邮箱地址';
    }
    return true;
});

然后在main.ts里引入

import '@/utils/validate'

使用

<template>
      <Form class="flex flex-col text-white w-full px-8" @submit="onLogin()">
        <div class="flex items-center pb-2 relative" style="border-bottom: 1px solid white">
          <label>邮箱</label>
          <Field class="border-none ml-3 bg-transparent focus:outline-none text-primary-smallTitle" name="email" rules="email" type="email" v-model="formState.email"></Field>
          <ErrorMessage name="email" class="error" />
        </div>
        <button class="w-full text-white bg-purple-300 py-3 mt-12 border-none rounded-lg hover:bg-purple-400 cursor-pointer">登录</button>
      </Form>
</template>
<script lang="ts" setup>
import { reactive } from 'vue';
import { Form, Field, ErrorMessage } from 'vee-validate';
 
 
interface UserForm {
  email: string;
}
 
const formState = reactive<UserForm>({
  email: ''
});
 
const onLogin =() => {
  console.log(formState);
  
};
 
</script>
<style scoped>
.error {
  color: red;
  position: absolute;
  bottom: -20px;
  left: 0;
  font-size: 14px;
}
</style>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文