Vue.jsとVuelidateを使用したモデルベースのフォーム検証
Vue.jsでフォームを検証するための最も初心者に優しいアプローチは、テンプレートベースのフォームを使用することですが、はるかに柔軟な方法は、代わりにモデルを検証することです。 モデルベースの検証は、大規模なアプリでは理解しやすく変更しやすい傾向があり、視覚的な混乱をテンプレートからモデルに移動して大幅に削減します。 Vue でこれを実現するための最もよく知られているライブラリは、Vuelidateを使用することです。
インストール
いつものように、VuelidateはNPMまたはYarnからインストールできます。
# Yarn $ yarn add vuelidate # NPM $ npm install vuelidate --save
次に、アプリのブートストラップで、Vuelidateプラグインを有効にします。
main.js
import Vue from 'vue'; import Vuelidate from 'vuelidate'; import App from 'App.vue'; Vue.use(Vuelidate); new Vue({ el: '#app', render: h => h(App) });
フィールド検証
フィールドを検証するには、dataモデルのプロパティの定義オブジェクトをコンポーネントのvalidationsプロパティに追加します。 次に、 vuelidate / lib / validations (または作成したカスタム関数)から検証関数をインポートします。 その後、通常どおりv-modelを介してデータプロパティにバインドできるようになります。 検証情報はthis。$v[propertyName]に保存されます。
$ vのスキーマ:
$v[propertyName]: { $dirty: boolean, // Whether or not this field has been interacted with yet. $invalid: boolean, // If this field is current valid or invalid, regardless of whether or not it is "dirty" $error: boolean, // Shortcut for $invalid && $dirty $pending: boolean, // Whether or not there is a pending validation (for async validations) $each: object // Holds all the validations for looped models. [YourValidationName]: boolean // The state of the validations defined on this property validations. (ie. if you have the 'required' validator, there would be a boolean 'required' property here, and so forth.) [Nested]: object // You can nest values in your model here as well, and the validation properties will be added to each nested field. }
<template> <form> <input type="text" v-model="emailValue"/> <p v-if="!$v.emailValue.required">The email field is required!</p> <p v-if="!$v.emailValue.email">The input must be a proper email!</p> </form> </template> <script> import { required, email } from 'vuelidate/lib/validations' export default { data() { return { emailValue: '' } }, validations: { emailValue: { required, email } } } </script>
組み込みのバリデーター
Vuelidate は、デフォルトでこれらのバリデーターを提供します。 それらはvuelidate/ lib /validatorsからインポートできます。 Webpack 2またはロールアップとツリーシェイクを使用している場合、プロジェクトで使用されていないバリデーターはバンドルされません。
- required()-このフィールドを空にすることはできません。
- minLength(length:number)-フィールドの最小の長さ。 文字列と配列で動作します。
- maxLength(length:number)-フィールドの最大長。 文字列と配列で動作します。
- between(min、max)-数値は最小値と最大値の間にある必要があります。
- alpha()-英字のみを使用できます。
- alphaNum()-英数字のみを許可します。
- email()-有効なメールのみを許可します。
- sameAs(fieldName:string | getFieldName:function-> string)-fieldNameまたは関数で指定された別のフィールドと同じ入力を要求できます。
- または(validators…)-指定されたバリデーターの少なくとも1つが有効な場合に有効です。
- and(validators…)-指定されたすべてのバリデーターが有効な場合に有効です。
カスタム検証者
Vuelidateのカスタムバリデーターは、ブール値またはブール値に解決されるpromiseを返す関数です。
フィールドに「tom」という単語のみが含まれるようにする場合は、次のようなバリデーターを作成できます。
tom-validator.js
export const TomValidator = (value, component) => { return value === 'tom'; }
MyComponent.vue
... <script> import { TomValidator } from './tom-validator'; export default { data() { return { inputField: '' } }, validators: { inputField: { TomValidator } } } </script>
さらに一歩進んで、一致する必要のある文字列を指定できるようにすることもできます。 その場合は、バリデーター関数を返す高階関数を作成するだけです。
match-validator.js
export const MatchValidator = (stringToMatch) => { return (value, component) => value === stringToMatch; }
MyComponent.vue
... <script> import { MatchValidator } from './match-validator'; export default { data() { return { inputField: '' } }, validators: { inputField: { MatchValidator: MatchValidator('rupert') // Only allows inputField to contain 'rupert.' One might Wonder why the field even exists then... } } } </script>