We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
2020 / 04 / 25
Validate a required boolean in Vue
Useful when making sure checkboxes have been ticked
Required booleans
Let’s say you have a checkbox that you need your users to click/check 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 it’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 other values
the model can contain, such as null
or undefined
.
What we need to check here, is whether the value of the
model is equal to true
or not.
Let’s 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! :sunglasses: