Skip to content

Vuelidate – Hướng dẫn Input Validator cho Vuejs

Vuelidate là một thư viện hỗ trợ cho Vue 2.0 & 3.0 kiểm tra form input, đồng thời cung cấp cách thức hiển thị lỗi (yêu cầu) một cách trực quan nhất.

So với đối thủ của nó VeeValidate – cũng là một input validator & display errors thì theo cảm nhận cá nhân : Vuelidate đơn giản hơn hẳn về cách hoạt động cũng như rất dễ dàng có thể tìm hiểu trong vài phút đọc document

Dưới đây là cách sử dụng Vuelidate đi với Vue 3.0 chưa được hỗ trợ hoàn toàn (*hi vọng có thể update post này trong tương lai :)) )


Install

npm install @vuelidate/core @vuelidate/validators

Setup

// main.js
import { createApp } from 'vue'
import App from './App.vue'
import { VuelidatePlugin } from '@vuelidate/core'

const app = createApp(App)
app.use(VuelidatePlugin) // bắt buộc đặt trước mount
app.mount('#app')

Usage

<script>
import { required } from '@vuelidate/validators'

export default {
  data() {
    return {
      name: ''
    }
  },
  validations() {
    return {
      name: { required }
    }
  }
}
</script>

Active Dirty

<input v-model="name" @input="$v.name.$touch">

//or
methods: {
  makeDirty() {
    this.$v.name.$touch()
  }
}

v-model

<template>
  <input v-model="$v.name.$model">
</template>

Sử dụng $model sẽ tự động $touch mỗi khi update, thay đổi field v.v

Alway Dirty

<input v-model="name">

export default {
  validations() {
    return {
      name: { required, $autoDirty: true },
    }
  }
}

Reset state

<app-modal @closed="$v.$reset()">
  <!-- some inputs  -->
</app-modal>

Display error

<p
  v-for="(error, index) of $v.$errors"
  // hoặc
  v-for="(error, index) of $v.name.$errors"


  :key="index"
>
  <strong>{{ error.$validator }}</strong>
  <small> on property</small>
  <strong>{{ error.$property }}</strong>
  <small> says:</small>
  <strong>{{ error.$message }}</strong>
</p>

onSubmit

export default {
  methods: {
    submitForm() {
      this.$v.$touch()
      if(this.$v.$error) return
      // do stuff
    }
  }
}

Async Validating

export default {
  methods: {
    async submitForm() {
      if(! await this.$v.$validate()) return
      // do stuff
    }
  }
}

Composition API

import { ref } from 'vue' // or '@vue/composition-api' in Vue 2.x
import { useVuelidate } from '@vuelidate/core'
import { email, required } from '@vuelidate/validators'

export default {
  setup () {
    const name = ref('')
    const emailAddress = ref('')
    const rules = {
      name: { required },
      emailAddress: { required, email }
    }

    const v = useVuelidate(rules, { name, emailAddress })

    return { name, emailAddress, v }
  }
}

Nest Validation

When using useVuelidate, Vuelidate will collect all validation $errors from all nested components. No need to pass any props or listen to any events.

<template>
  <div>
    <CompA />
    <CompB />

    <p v-for="(error, index) of v.$errors" :key="index">
      {{ error.$message }}
    </p>
  </div>
<template>

<script>
import { useVuelidate } from '@vuelidate/core'

export default {
  setup () {
    const v = useVuelidate() // this will contain all $errors from both <CompA> and <CompB>

    return { v }
  }
}
</script>

Built-in Validator

NameMeta parametersDescription
requirednoneRequires non-empty data. Checks for empty arrays and strings containing only whitespaces.
requiredIflocator*Requires non-empty data only if provided property or predicate is true.
requiredUnlesslocator*Requires non-empty data only if provided property or predicate is false.
minLengthminRequires the input to have a minimum specified length, inclusive. Works with arrays.
maxLengthmaxRequires the input to have a maximum specified length, inclusive. Works with arrays.
minValueminRequires entry to have a specified minimum numeric value or Date.
maxValuemaxRequires entry to have a specified maximum numeric value or Date.
betweenmin, maxChecks if a number or Date is in specified bounds. Min and max are both inclusive.
alphanoneAccepts only alphabet characters.
alphaNumnoneAccepts only alphanumerics.
numericnoneAccepts only numerics.
integernoneAccepts positive and negative integers.
decimalnoneAccepts positive and negative decimal numbers.
emailnoneAccepts valid email addresses. Keep in mind you still have to carefully verify it on your server, as it is impossible to tell if the address is real without sending verification email.
ipAddressnoneAccepts valid IPv4 addresses in dotted decimal notation like 127.0.0.1.
macAddressseparator=’:’Accepts valid MAC addresses like 00:ff:11:22:33:44:55. Don’t forget to call it macAddress(), as it has optional parameter. You can specify your own separator instead of ':'. Provide empty separator macAddress('') to validate MAC addresses like 00ff1122334455.
sameAslocator*Checks for equality with a given property.
urlnoneAccepts only URLs.
orvalidators…Passes when at least one of provided validators passes.
andvalidators…Passes when all of provided validators passes.
notvalidatorPasses when provided validator would not pass, fails otherwise. Can be chained with other validators like not(sameAs('field')).
withParams$params, validatorNot really a validator, but a validator modifier. Adds a $params object to the provided validator. Can be used on validation functions or even entire nested field validation objects. Useful for creating your own custom validators.

State values

$invalidbooleanIndicates the state of validation for given model becomes true when any of it’s child validators specified in options returns a falsy value. In case of validation groups, all grouped validators are considered.
$dirtybooleanA flag representing if the field under validation was touched by the user at least once. Usually it is used to decide if the message is supposed to be displayed to the end user. You can manage this flag manually by using $touch and $reset methods. It is set automatically when writing to $model value. The $dirty flag is considered true if given model was $touched or all of it’s children are $dirty.
$anyDirtybooleanA flag very similar to $dirty, with one exception. The $anyDirty flag is considered true if given model was $touched or any of it’s children are $anyDirty.
$modelanyA reference to the original validated model. Reading this value will always give you exactly the same value as if you referenced the model directly. That means this.$v.value.$model is equivalent to this.value when read. Writing to that value will update the model and invoke $touch method automatically. This is very useful to use as v-model payload, providing a way of automatically marking given field as $dirty on first touch. Pairs well with .lazy modifier.
$errorbooleanConvenience flag to easily decide if a message should be displayed. Equivalent to this.$dirty && !this.$pending && this.$invalid.
$errorsArrayCollection of all the error messages, collected for all child properties and nested forms (Vue components).
$anyErrorbooleanConvenience flag to easily decide if a message should be displayed. A variant that considers error to be displayed when itself or at least one of its children has $error equal to true.
$pendingbooleanIndicates if any child async validator is currently pending. Always false if all validators are synchronous.
$paramsobjectContains types and parameters of all provided validators at the current level, as well as types and parameters of child validation groups, which may be declared using withParams. Useful as an input to your error rendering system. Safe to use in translated text.

Validation Method

$validatefunctionTriggers all validators if not triggered already. Returns a Promise with a boolean, which resolves once all validators finish.
$touchfunctionset $dirty = true
$getResultsForChildfunctionRetrieves the validation results for a nested form component.
$resetfunctionreset validation
Published inVuelidate

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *