Vuelidate Validate During Submit (Server Validation) Programatically

Apr 16, 2020

Technically, there is no API to perform validation or trigger error programatically, but we can hack around it with custom validation rules.

  • The validation error is cleared once the model value changed
  • If you would like to retry/resubmit again without changing the value (maybe some server error not due to errorness value), don't use this kind of validation (use a popup/toast to show the error instead)
<template>  <b-form inline class="justify-content-center" ref="form" @submit.prevent="submit">    <b-form-group  label="Email" label-sr-only label-for="input-email">      <b-input          :state="validateState($"          v-model="$$model"          id="input-email"          placeholder="Your email"        ></b-input>      <b-button type="submit" variant="primary">Request Invite</b-button>      <b-form-invalid-feedback v-if="!$">Invalid email address.</b-form-invalid-feedback>      <b-form-invalid-feedback v-if="!$">This is a required field.</b-form-invalid-feedback>      <b-form-invalid-feedback v-if="!$">{{  submitErrorMessage }}</b-form-invalid-feedback>    </b-form-group>  </b-form></template><script>import { validationMixin } from "vuelidate"import { required, email } from "vuelidate/lib/validators"const submitOk = (value, vm) => {  if (vm.submitError) {    // clear error after 1st display    const error = vm.submitError    vm.submitErrorMessage = error    vm.submitError = false    return false  }  return true}export default {  mixins: [validationMixin],  data() {    return {      email: null,      submitError: false,      submitErrorMessage: null    }  },  validations: {    email: {      required,      email,      submitOk    },  },  methods: {    validateState(item) {      const { $dirty, $error } = item      return $dirty ? !$error : null    },    async submit() {      // perform custom validation or server validation      if ( == '[email protected]') {        this.submitError = 'Email already exist'        return      }      alert('OK')    }  }}</script>

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.