lobo_tuerto's notes
for greatly improving DX
Blog
Notes
About

Validate a required boolean in Vue

This is useful when validating that checkboxs have been ticked.

📅Date25 April 2020
🏷️
frontendvuevuelidate

Required booleans

Let’s say you have a checkbox that you need your users to click on before proceeding —like accepting some ToS or agreeing to something.

This falls on the realm of form validation, and there is nothing better than Vuelidate for that.

If you already know some Vuelidate you might be tempted to go with something like:

<!-- template... -->

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

export default {
  data () {
    return {
      hasAccepted: false
    }
  },

  validations: {
    hasAccepted: { required }
  }
}
</script>

But you just can’t use the required validator on a checkbox —or switch. That’s because that’s a boolean.

The model for those would contain a boolean value, true or false, and either would make the validation pass since those values are different from null or undefined.

What we need to check here, is whether the value of the model is equal to true or not.

You need to do something like this instead:

<!-- template... -->

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

export default {
  data () {
    return {
      hasAccepted: false
    }
  },

  validations: {
    hasAccepted: {
      accepted: val => val === true
    }
  }
}
</script>

Source code

Here is the source code for a working example:

<template lang="pug">
.simple-required-boolean-good.mb-8
  v-card
    v-card-title Example #2
    v-card-text
      v-switch(
        v-model="$v.hasAccepted.$model"
        :error="$v.hasAccepted.$error"
        :hint="hintText"
        label="Do you accept?"
        persistent-hint
      )
      v-checkbox(
        v-model="$v.hasAccepted.$model"
        :error="$v.hasAccepted.$error"
        :hint="hintText"
        label="Do you accept?"
        persistent-hint
      )
</template>


<script>
export default {
  data () {
    return {
      hasAccepted: false
    }
  },

  computed: {
    hintText () {
      const value = `value: ${this.hasAccepted}`
      const invalid = `invalid: ${this.$v.hasAccepted.$invalid}`
      const error = `error: ${this.$v.hasAccepted.$error}`

      return `${value} -> ${invalid} -> ${error}`
    }
  },

  validations: {
    hasAccepted: {
      accepted: val => val === true
    }
  }
}
</script>

That’s it! 😎


Got comments or feedback?
Follow me on
rev-7175614