ホームページ  >  記事  >  ウェブフロントエンド  >  vue3+async-validator がフォーム検証を実装する方法

vue3+async-validator がフォーム検証を実装する方法

PHPz
PHPz転載
2023-05-11 09:55:122831ブラウズ
    #vue3 プロジェクトをビルドする

    プロジェクトを作成する前に、ここで最初に説明する必要があるのは、使用するバージョンです

    • Nodejs: v17.5.0

    • ##pnpm: 7.0.0

    • Vue: 3.2.25

    • まず、Vite は
    FormValidate

    という名前の vue3 プロジェクト デモを作成します。コマンド ラインにコマンド

    pnpm create vite FormValidate

    を入力して Enter を押します 次に、vue

    を選択して Enter キーを押し続けます。最初に

    FormValidate

    (フォーム検証) プロジェクトを作成しました #コマンド ライン プロンプトに従って、プロジェクトのルート ディレクトリを入力し、コマンド pnpm install

    を使用してインストールしますプロジェクトに必要な依存関係。もちろん、ここでは pnpm が使用されます。npm や Yarn よりもはるかに高速です。

    次に、プロジェクトを開始しますpnpm run dev

    。ターミナルの出力は次の図のようになります。

     vite v2.9.7 dev server running at:
      > Local: http://localhost:3000/
      > Network: use `--host` to expose
      ready in 954ms.
    参照を開始してアドレスを入力します http://localhost:3000 /

    わかりました。プロジェクトのセットアップが完了しました。一日の終わりに、今日のトピックであるフォーム検証#について話し始めます。

    ##vue3 フォーム検証ここでは async-validator を使用します。これはフォームの非同期検証用のプラグインです。github で 5,000 個のスターを獲得しており、次のように広く使用されています。

    Ant.design

    Element UI

    Naive UI などはすべてこのプラグインを使用しており、一部の Nodejs バックエンド プロジェクトでもこれを使用しています。プラグイン。 最初にこのプラグインをインストールし、

    pnpm install async-validator

    ここにasync-validator バージョンを入力します。コマンド ライン はい

    4.1.1

    1. フォーム コードプロジェクトで App.vue ファイルを開き、冗長なファイルの内容を削除し、タイトルを入力します

    vue3 フォーム検証

    そして、初期コードを追加します

    <template>
        <div class="main">
            <h4>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>

    少し見苦しく見えますか? 心配しないで、単に美しくするために CSS コードを追加しましょう

    <template>
        <div class="main">
            <h4>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。検証の追加

    2-1. 初期化

    では

    ref
    属性と
    async-validator

    を導入しますが、ここでは v-model## を追加します。 # 各入力ボックスにバインディング 定義された属性、

    // 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,
    })
    フォームの状況に応じて、検証が必要なオブジェクトと検証失敗時の情報を格納するオブジェクトを定義します
    const rules = {
        account: { required: true, message: &#39;请输入账号&#39; },
        password: { required: true, message: &#39;请输入密码&#39; }
    }
    スキーマとルールをインスタンス化します。スキーマを渡してバリデータを取得します。
    const validator = new Schema(rules)

    使用する単一のフォームを検証するには、

    ロスト フォーカス イベント

    、関数を定義し、この関数を out に追加します。アカウント入力のフォーカス イベント

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

    次に、インスタンス化されたバリデーター関数を handleBlurAccount

    const handleBlurAccount = () => {
        validator.validate({account: form.value.account}, (errors, fields) => {
            if (errors && fields.account) {
                console.log(fields.account[0].message);
                return errors
            }
        })
    }
    アカウントの入力でテストすると、アカウント番号を入力してください## ことがわかります。コンソールに出力 # 言葉を待ちます

    同様に、パスワードボックスに次のコードを追加します

    //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. 複数フォームの検証もちろんです, ここでは 1 つの入力のみが検証されます はい、次に複数のフォームの検証について話しましょう。クリック イベントを送信として定義し、送信イベントをボタンに追加します。そしてもちろん、ブラウザのデフォルト イベントを防ぐことを忘れないでください

    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 メソッド

    上記のメソッドを確認した後、
    async-validator

    も Promise メソッドを提供するため、submit 関数のコードを次のように変更します

    validator.validate(form.value).then((value) => {
            // 校验通过
            console.log(value);
    }).catch(({ errors, fields }) => {
        console.log(errors);
        return errors
    })
    同じように [保存] をクリックします。コンソールにエラー メッセージが表示され、記述した内容が適切であることがわかります。

    2-4定期的な検証

    もちろん、メール アドレスや電話番号などのフォームが入力されることもあります。このとき、定期的な検証ルールを追加する必要があります。最初に 2 つのフォームを追加し、アウトを追加します。フォーカスのイベント。通常の検証には

    async-validatorvue3+async-validator がフォーム検証を実装する方法 パターンの属性が必要です。要件を満たす通常のルールをルールに追加します。コードは次のとおりです。

    <div class="form-group ">
        <label class="label">电话号码</label>
        <input v-model="form.phone" type="text" class="input" @blur="handleBlurPhone"
                        placeholder="请输入电话号码" />
    </div>
    
    <div class="form-group ">
        <label class="label">邮箱</label>
        <input v-model="form.email" type="text" class="input" @blur="handleBlurEmail"
                        placeholder="请输入邮箱" />
    </div>
    
    
    const form = ref({
        account: null,
        email: null,
        password: null,
    })
    
    const rules = {
        account: { required: true, message: &#39;请输入账号&#39; },
        phone: {
            required: true,
            pattern: /^1\d{10}$/,
            message: "请输入电话号码"
        },
        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: "请输入邮箱"
        },
        password: { required: true, message: &#39;请输入密码&#39; }
    }
    
    const handleBlurPhone = () => {
        validator.validate({ phone: form.value.phone }, (errors, fields) => {
            if (errors && fields.phone) {
                console.log(errors, fields);
                console.log(fields.phone[0].message);
                return errors
            }
        })
    }
    const handleBlurEmail = () => {
        validator.validate({ email: form.value.email }, (errors, fields) => {
            if (errors && fields.email) {
                console.log(errors, fields);
                console.log(fields.email[0].message);
                return errors
            }
        })
    }
    もちろん、テストに問題はありません

    2-5. 長さ制御フォーム入力コンテンツの長さを制御するには、属性 min と max を使用できます。アカウント フォームを使用します。例として、これら 2 つの属性をルール オブジェクトのアカウントに追加します。たとえば、次のように、アカウントは少なくとも 5 文字、最大 10 文字である必要があります

    account: { required: true, min:5, max:10, message: &#39;请输入账号&#39; }

    ユーザーの入力を制御する入力のネイティブ属性 maxLength="10"

    #2-6. 複数の検証条件
    #複数の検証がある場合 条件を設定するときに、ルールの検証条件を記述することができます配列として。引き続きアカウント フォームを例として使用します。たとえば、アカウント要件は中国語である必要があり、アカウント番号は少なくとも 5 文字、最大 10 文字である必要があります。コードは次のとおりです

    account: [
        { required: true, min:5, max:10, message: &#39;请输入账号&#39; },
        { required: true, pattern: /[\u4e00-\u9fa5]/, message: &#39;请输入中文账号&#39; }
    ],

    2-5. カスタム検証

    特殊な検証状況に合わせてカスタム検証関数を使用することもありますが、このときは次のようにすることができます
    field:{
        required: true,
        validator(rule, value, callback){
          return value === &#39;&#39;;
        },
        message: &#39;值不等于 "".&#39;,
    }
    ここでは、 vue3 のフォーム検証機能はほぼ完成したので、検証機能を改良していきます

    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;
    }

    以上がvue3+async-validator がフォーム検証を実装する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

    声明:
    この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。