javascriptvue.jsvuejs3yupvee-validate

How to require at least one checkbox be checked using Yup and VeeValidate with Vue 3?


I am trying to ensure a user checks at least one checkbox. The web API I am calling requires at least one value be passed in an array of strings. For this example, the user must choose at least one favorite color where the web API expects at least one of red, green or blue, e.g. { "colors": ["red"] } would be valid, but { "colors": [] } would not.

I am using:

The code I am using:

<template>
  <Form id="app-form" @submit="onSubmit" @invalid-submit="onInvalidSubmit" v-slot="{ values, errors }" :validation-schema="rules">
    <fieldset>
      <legend>Choose your favorite colors:</legend>

      <label>
        <Field type="checkbox" name="colors[0]" value="red" /> Red<br>
      </label>

      <label>
        <Field type="checkbox" name="colors[1]" value="green" /> Green<br>
      </label>

      <label>
        <Field type="checkbox" name="colors[2]" value="blue" /> Blue<br>
      </label>

      <ErrorMessage name="colors" />
    </fieldset>

    <p>
      <button type="submit">Save Preferences</button>
    </p>
  </Form>
</template>

<script setup>
import { array, date, object, string } from 'yup';

const rules = object().shape({
  colors: array(string()).required('Choose at least one color.')
});
</script>

<script>
  import { Form, Field, ErrorMessage } from 'vee-validate';
  import { configure } from 'vee-validate';

  configure({
    validateOnBlur: false,
    validateOnChange: false
  });

  export default {
    name: 'AppForm',
    components: {
      Form,
      Field,
      ErrorMessage
    },
    methods: {
      onSubmit(values) {
         console.log('Form submitted without errors.');
      },
      onInvalidSubmit(form) {
        console.log('form is invalid', form);
      }
    }
  }
</script>

In the browser's console, the onInvalidSubmit method is not being called as I expected when no checkboxes are checked. Instead, the onSubmit method is called and I see Form submitted without errors in the browser's console.

Some other variations I tried:


// form was valid without check marking anything
const rules = object().shape({
  colors: array(string())
    .ensure()
    .required('Choose at least one color.')
});

// form was invalid, but every checkbox said it was required, which is not what I want.
const rules = object().shape({
  colors: array(string().required())
    .required('Choose at least one color.')
});


// form was valid without check marking anything
const rules = object().shape({
  colors: array(string())
    .ensure()
    .min(1, 'Choose at least 1.')
});

// form was invalid without check-marking anything, but was also invalid when check-marking 2 colors.
const rules = object().shape({
  colors: array(string())
    .ensure()
    .length(1)
});

How can I require at least one checkbox be checked using Yup, VeeValidate, and Vue?

I need two things to work:

  1. The form is invalid if no checkboxes are marked.
  2. When no check boxes are marked, display an error message to the user.
    • Note: Use of the <ErrorMessage /> tag is optional as long as I can show the message.

I am very new to Vue. I've cobbled together what appears to be a cohesive set of tools, but I just might not be using them right. I feel like I'm fighting the framework here.


Solution

  • Ok, like usual I figured out the answer 5 minutes after I posted my question. I was fighting the framework, just not in the way I assumed. The fix involved two changes to my code:

    1. The <Field /> names should not be using bracket notation for the name attribute. Each field tag should be <Field name="colors" /> instead of <Field name="colors[n]" /> (where you replace n with an integer starting with zero).

    2. It appears that both min() and required() are needed to get this working correctly.

    The full working code:

    <template>
      <Form id="app-form" @submit="onSubmit" @invalid-submit="onInvalidSubmit" v-slot="{ values, errors }" :validation-schema="rules">
        <fieldset>
          <legend>Choose your favorite colors:</legend>
    
          <!-- field name attributes should be "colors" not "colors[n]" -->
    
          <label>
            <Field type="checkbox" name="colors" value="red" /> Red<br>
          </label>
    
          <label>
            <Field type="checkbox" name="colors" value="green" /> Green<br>
          </label>
    
          <label>
            <Field type="checkbox" name="colors" value="blue" /> Blue<br>
          </label>
    
          <p>
            <ErrorMessage name="colors" />
          </p>
        </fieldset>
    
        <p>
          <button type="submit">Save Preferences</button>
        </p>
      </Form>
    </template>
      
    <script setup>
      import { array, date, object, string } from 'yup';
      
      const rules = object().shape({
        colors: array(string())
          // Both rules are needed together
          .required('Choose at least one color.')
          .min(1, 'Choose at least one color.')
      });
    </script>
      
    <script>
        import { Form, Field, ErrorMessage } from 'vee-validate';
        import { configure } from 'vee-validate';
      
        configure({
          validateOnBlur: false,
          validateOnChange: false
        });
      
        export default {
          name: 'AppForm',
          components: {
            Form,
            Field,
            ErrorMessage
          },
          methods: {
            onSubmit(values) {
               console.log('Form submitted without errors.', values);
            },
            onInvalidSubmit(form) {
              console.log('form is invalid', form);
            }
          }
        }
    </script>
    

    Without both min() and required(), different interactions with the checkbox group produced inconsistent validations according to the rules I was given. Required is truthy, which works the first time you submit the form without ever checking a checkbox. Check a box, submit, uncheck a box, then re-submit? Nope. The required() rule is satisfied since the reactive state now has an empty array in it (which is truthy).

    Just having min() by itself allowed you to submit the form without errors as long as you never toggled a checkbox. As soon as you check, then uncheck one of the checkboxes, the min() rule kicks in.

    Even adding a call to ensure() before calling min() and required() didn't fix this. The magic combo is:

    array(string())
      .required('Choose at least one color.')
      .min(1, 'Choose at least one color.')
    

    A little copy-pasta with the message is necessary to get the user experience consistent between the two rules.