search
HomeWeb Front-endVue.jsHow vue3+async-validator implements form validation

How vue3+async-validator implements form validation

May 11, 2023 am 09:55 AM
vue3asyncvalidator

    Build a vue3 project

    Before creating the project, the first thing we need to explain here is the version we use

    • Nodejs: v17.5.0

    • ##pnpm: 7.0.0

    • Vue: 3.2.25

    First of all, we Vite creates a vue3 project demo named

    FormValidate, we Enter the command

    pnpm create vite FormValidate on the command line and press Enter

    Then select vue

    and continue to press Enter, indicating that we have initially created

    FormValidate (Form Validation) Project

    According to the command line prompts, we enter the project root directory, and then use the command

    pnpm install to install the dependencies required for the project. Of course, pnpm is used here. Much faster than npm or yarn.

    Next, we start the project

    pnpm run dev, and the output in the terminal is as shown in the figure

     vite v2.9.7 dev server running at:
      > Local: http://localhost:3000/
      > Network: use `--host` to expose
      ready in 954ms.

    Start browsing and enter the address

    http://localhost:3000 /

    ok, here we have set up the project. At the end of the day, we will start to talk about our topic today-

    Form verification

    vue3 Form validation

    Here we use async-validator. This is a plug-in for asynchronous validation of forms. It has 5k stars on github and is also widely used, such as

    Ant.design, Element UI, Naive UI, etc. are all using this plug-in, and even some Nodejs back-end projects are also using this plug-in.

    First install this plug-in, enter

    pnpm install async-validator

    here

    async-validator version on the command line Yes4.1.1

    1. Form code

    Open the App.vue file in the project, delete the redundant file content, and enter the title

    vue3 form verification, and add some initial code

    <template>
        <div class="main">
            <h4 id="vue-nbsp-表单验证">vue3 表单验证</h4>
    
            <form>
                <div>
                    <label class="label">账号</label>
                    <input  type="text"  placeholder="请输入账号" class="input" />
                </div>
                <div>
                    <label class="label">密码</label>
                    <input  tyep="password" type="text" class="input"  placeholder="请输入密码"  />
                </div>
    
                <div>
                    <button>保存</button>
                </div>
            </form>
        </div>
    </template>
    <script setup>
    
    </script>
    <style lang="css">
    .main{
        text-align:center;
    }
    .label {
        padding-right: 10px;
        padding-left: 10px;
        display: inline-block;
        box-sizing: border-box;
        width: 100px;
        text-align: right;
    }
    .input {
        width: 200px;
        height: 30px;
        margin-top:10px;
    }
    </style>

    Does it look a bit ugly? Don’t worry, let’s add some css code to simply beautify it

    <template>
        <div class="main">
            <h4 id="Vue-表单验证">Vue3表单验证</h4>
    
            <form class="form-box">
                <div class="form-group ">
                    <label class="label">账号</label>
                    <input type="text" class="input" placeholder="请输入账号"  />
                </div>
                <div class="form-group">
                    <label class="label">密码</label>
                    <input  tyep="password" type="text"  placeholder="请输入密码" class="input" />
                </div>
    
                <div class="form-group">
                    <button class="btn ">保存</button>
                </div>
            </form>
        </div>
    </template>
    <script setup>
    
    </script>
    <style scoped>
    .main {
        text-align: center;
    }
    .btn{
        margin: 0;
        line-height: 1;
        padding: 15px;
        height: 30px;
        width: 60px;
        font-size: 14px;
        border-radius: 4px;
        color: #fff;
        background-color: #2080f0;
        white-space: nowrap;
        outline: none;
        position: relative;
        border: none;
        display: inline-flex;
        flex-wrap: nowrap;
        flex-shrink: 0;
        align-items: center;
        justify-content: center;
        user-select: none;
        text-align: center;
        cursor: pointer;
        text-decoration: none;
    }
    .form-box{
        width: 500px;
        max-width: 100%;
        margin: 0 auto;
        padding: 10px;
    }
    .form-group{
        margin: 10px;
        padding: 10px 15px 10px 0
    }
    .label {
        padding-right: 10px;
        padding-left: 10px;
        display: inline-block;
        box-sizing: border-box;
        width: 110px;
        text-align: right;
    }
    
    .input {
        width: calc(100% - 120px);
        height: 28px;
    }
    </style>

    2. Add verification

    2-1. Initialization
    introduces

    ref attributes and async-validator, here we add v-model binding to each input box Defined attributes,

    // html
    <input type="text" v-model="form.account" class="input" placeholder="请输入账号"  />
    <input  tyep="password" v-model="form.password" type="text"  placeholder="请输入密码" class="input" />
    // script
    import { ref } from "vue"
    import Schema from &#39;async-validator&#39;;
    
    const form = ref({
        account: null,
        password: null,
    })

    According to the situation of the form, we define an object, which stores the objects that need to be verified and the information when the verification fails

    const rules = {
        account: { required: true, message: &#39;请输入账号&#39; },
        password: { required: true, message: &#39;请输入密码&#39; }
    }

    Instantiate the Schema, and rules Pass in Schema and get a validator

    const validator = new Schema(rules)

    To verify a single form we use

    lost focus event, define a function, and add this function to the out of focus event on the account input

    // html
    <input v-model="account" type="text" class="input" @blur="handleBlurAccount" placeholder="请输入账号"  />
    // script
    const handleBlurAccount = () => {}

    Then write the instantiated validator function into handleBlurAccount

    const handleBlurAccount = () => {
        validator.validate({account: form.value.account}, (errors, fields) => {
            if (errors && fields.account) {
                console.log(fields.account[0].message);
                return errors
            }
        })
    }

    Test in the input of account, we can see that

    Please enter the account number## printed on the console # Wait for the words Similarly, we also add the following code to the password box

    //html
    <input v-model="form.password" tyep="password" type="text" @blur="handleBlurPassword"  placeholder="请输入密码" class="input" />
    //script
    const handleBlurPassword = () => {
        validator.validate({password: form.value.password}, (errors, fields) => {
            if (errors && fields.password) {
                console.log(errors, fields);
                console.log(fields.password[0].message);
                return errors
            }
        })
    }

    2-2. Verification of multiple forms

    Of course, only a single input is verified here Yes, let’s talk about the verification of multiple forms next. Define a click event as submit, add the submit event to the button, and of course don’t forget to prevent the browser default event
    const submit = (e) => {
        e.preventDefault();
        validator.validate(form.value, (errors, fields) => {
            if (errors) {
                for(let key of errors) {
                    console.log(key.message);
                }
                return errors
            }
        })
    }

    2-3. Promise method After verifying

    the above method,
    async-validator

    also provides the Promise method, we modify the code in the submit function as follows <pre class='brush:php;toolbar:false;'>validator.validate(form.value).then((value) =&gt; { // 校验通过 console.log(value); }).catch(({ errors, fields }) =&gt; { console.log(errors); return errors })</pre>Click save, the same, We can see that the error message has been printed on the console, indicating that what we wrote is appropriate

    How vue3+async-validator implements form validation2-4. Regular verification

    Of course sometimes we Forms such as email addresses, phone numbers, etc. will be entered. At this time, we need to add regular rules for verification. We first add two forms and add out-of-focus events. Regular verification requires the attributes of
    async-validator

    pattern, we will add the regular rules that meet the requirements to rules. The code is as follows<pre class='brush:php;toolbar:false;'>&lt;div class=&quot;form-group &quot;&gt; &lt;label class=&quot;label&quot;&gt;电话号码&lt;/label&gt; &lt;input v-model=&quot;form.phone&quot; type=&quot;text&quot; class=&quot;input&quot; @blur=&quot;handleBlurPhone&quot; placeholder=&quot;请输入电话号码&quot; /&gt; &lt;/div&gt; &lt;div class=&quot;form-group &quot;&gt; &lt;label class=&quot;label&quot;&gt;邮箱&lt;/label&gt; &lt;input v-model=&quot;form.email&quot; type=&quot;text&quot; class=&quot;input&quot; @blur=&quot;handleBlurEmail&quot; placeholder=&quot;请输入邮箱&quot; /&gt; &lt;/div&gt; const form = ref({ account: null, email: null, password: null, }) const rules = { account: { required: true, message: &amp;#39;请输入账号&amp;#39; }, phone: { required: true, pattern: /^1\d{10}$/, message: &quot;请输入电话号码&quot; }, email: { required: true, pattern: /^([a-zA-Z0-9]+[_|_|\-|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,6}$/, message: &quot;请输入邮箱&quot; }, password: { required: true, message: &amp;#39;请输入密码&amp;#39; } } const handleBlurPhone = () =&gt; { validator.validate({ phone: form.value.phone }, (errors, fields) =&gt; { if (errors &amp;&amp; fields.phone) { console.log(errors, fields); console.log(fields.phone[0].message); return errors } }) } const handleBlurEmail = () =&gt; { validator.validate({ email: form.value.email }, (errors, fields) =&gt; { if (errors &amp;&amp; fields.email) { console.log(errors, fields); console.log(fields.email[0].message); return errors } }) }</pre>Of course, there is no problem with the test

    2-5. Length control

    If you To control the length of form input content, you can use the attributes min and max. We use the account form as an example. We add these two attributes to the account of the rules object. For example, the account is required to be at least 5 characters and at most 10 characters, as follows
    account: { required: true, min:5, max:10, message: &#39;请输入账号&#39; }

    We can also use the native attribute maxLength="10" of input to control the user's input

    2-6. Multiple verification conditions

    When we have multiple verifications When setting conditions, we can write the verification conditions of rules as an array. We still use the account form as an example. For example, the account requirement must be in Chinese, and the account number must be at least 5 characters and at most 10 characters. The code is as follows
    account: [
        { required: true, min:5, max:10, message: &#39;请输入账号&#39; },
        { required: true, pattern: /[\u4e00-\u9fa5]/, message: &#39;请输入中文账号&#39; }
    ],

    2-5. Custom verification

    Sometimes, we will use a custom verification function to meet special verification situations. At this time, we can do this
    field:{
        required: true,
        validator(rule, value, callback){
          return value === &#39;&#39;;
        },
        message: &#39;值不等于 "".&#39;,
    }

    Here, the prototype of vue3's form verification function has basically come out. Now we will improve the verification function

    3.优化完善

    之前的表单验证虽然已经做出了,但是校验的提示信息是在控制台,这个很不友好,用户也看不到提示,所以这里我们完善下这部分功能

    首先我们在 label 边加一个 "*" 表示必填,并且添加样式,给一个红色,醒目一些

    <label class="label">
        <span>账号</span>
        <span class="asterisk"> *</span>
    </label>
    .asterisk{
        color: #d03050;
    }

    我们考虑到 rules 对象中 required 属性的作用,这里使用 vue 的条件判断语句 v-if 来判断,先定义一个函数,名字就叫 getRequired,然后将 rules.account,作为参数传进去,这里要重点说明一下,如果考虑封装验证方法,这里可以不用传参,不多说,后面讲到了,我们再说,先看代码

     <span class="asterisk" v-if="getRequired(rules.account)"> *</span>
    const getRequired = (condition) => {
        if(Object.prototype.toString.call(condition) === "[object Object]") {
            return condition.required
        } else if (Object.prototype.toString.call(condition) === "[object Array]") {
            let result = condition.some(item => item.required)
            return result
        }
        return false
    }

    因为 rules.account, 有可能是对象或者数组,这里我们加一个判断区别下,如果传递进来的是对象,我们直接将属性required返回回去,至于required属性是否存在,这里没有必要多判断。 如果传递进来的是数组,我们使用 some 函数获取下结果,然后再返回.

    修改 rules.accountrequired 值为false,星号消失,这里只要有一个required 值为true,那么这个星号就显示

    我们接着来添加错误信息的显示与隐藏

    我们定义一个对象 modelControl,这个对象里面动态存储错误信息,

    const modelControl = ref({})

    接着给 accountinput 框添加一个自定义属性 prop, 属性值是 account, 再加一个div显示错误提示信息

    <div class="form-group">
        <label class="label">
            <span>账号</span>
            <span class="asterisk" v-if="getRequired(rules.account)"> *</span>
        </label>
        <input v-model="form.account" type="text" maxLength="10" class="input" prop="account" @blur="handleBlurAccount" placeholder="请输入账号" />
        <div class="input feedback" v-if="modelControl[&#39;account&#39;]">{{modelControl[&#39;account&#39;]}}</div>
    </div>
    
    .feedback{
        color: #d03050;
        font-size:14px;
        margin-top: 3px;
        text-align:left;
        margin-left:110px;
    }

    为了动态的显示和隐藏错误信息,我们需要修改失焦事件 和 submit 事件,在事件执行的时候,动态的将值赋予或清除,代码如下

    const handleBlurAccount = (e) => {
        const prop = e.target.attributes.prop.value
        if (!prop) {
            return false
        }
        validator.validate({ account: form.value.account }, (errors, fields) => {
            if (errors && fields.account) {
                console.log(errors, fields);
                console.log(fields.account[0].message);
    
                modelControl.value[prop] = fields[prop][0].message
                return errors
            }
            modelControl.value[prop] = null
        })
    }
    validator.validate(form.value).then((value) => {
            // 校验通过
        console.log(value);
    }).catch(({ errors, fields }) => {
        console.log(errors, fields);
        for(let key in fields) {
            modelControl.value[key] = fields[key][0].message
        }
        console.log(modelControl);
        return errors
    })

    到这里 表单的动态验证功能基本算是完成了,但是我们发现,每次错误信息的展示都会使得input框跳动,所以还得调整下样式

    .form-group {
        margin: 2px;
        padding: 10px 15px 3px 0;
        height:57px;
        transition: color .3s ease;
    }

    The above is the detailed content of How vue3+async-validator implements form validation. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Vue.js and the Frontend: A Deep Dive into the FrameworkVue.js and the Frontend: A Deep Dive into the FrameworkApr 22, 2025 am 12:04 AM

    Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

    The Power of Vue.js on the Frontend: Key Features and BenefitsThe Power of Vue.js on the Frontend: Key Features and BenefitsApr 21, 2025 am 12:07 AM

    Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

    Is vue.js better than React?Is vue.js better than React?Apr 20, 2025 am 12:05 AM

    Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

    Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

    Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

    Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

    Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

    Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

    Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

    Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

    Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

    The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

    Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools