question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Validation: at least one checkbox is checked

See original GitHub issue

I understand that this is not really a feature request nor a bug, but I don’t know where I could ask for some information :S

Is your feature request related to a problem? Please describe. Well my problem is that I would like to build a custom validator that validates if at least one of my checkboxes is checked. I realize that this subject was discussed before, but somehow I don’t fully understand.

I found the following links: https://jsfiddle.net/awolf2904/pndvq438/ https://codereview.stackexchange.com/questions/151988/custom-checkbox-validation-on-submit

Which seem to discuss this matter.

What I don’t understand:

  • Why does the validation has to be evoked manually? Why is it not just validated on user change on the checkboxes? – In this matter I also found this: Changing events per field where I would assume that the validation should be executed on each change of the input value.
  • Also I don’t understand how the validateAll is actually used. How should fields be passed into it? I always cause the script to break, because of endless loops.

I think some of my code could describe my problem better:

<template>
…
<div v-for="(list, index) in mailChimpLists" :key="index">
  <input
    :id="`NewsletterForm__list-id_${index}`"
    v-model="list.checked"
    v-validate ="'atLeastOne:list.checked'"
    data-vv-validate-on="change"
    type="checkbox"
    name="interest"
    :value="list.list_label"
  >
  <label :for="`NewsletterForm__list-id_${index}`">{{ list.list_label }}</label>
</div>
…
</template>

… 
  mounted() {
    Validator.extend('atLeastOne', {
      getMessage: field => 'at least one ' + field + ' has to be checked',
      validate: value => {
        this.log('value: ', value)
        return value || this.mailChimpLists.some(list => list.checked) // check if at least one is checked
      }
    })
  }

Whereas my data within mailChimpLists look like this:

mailChimpLists: [
  {
    checked:true
    list_label: "List 1",
    subscription_link: "https://…"
  },
  {
    list_label: "List 2",
    subscription_link: "https://wea…"
  }
]

Should my custom rule not return false if some() does not find any checked boxes? And this should then trigger an error?

Or is the validation not executed if there is no checkbox selected anymore?

Describe the solution you’d like In addition to get help with the above mentioned issue I would assume that susch a validation is needed quite often and could maybe become one of the standard validation rules?

I would be extremely grateful if someone could help me out with this and give me a little hint. Cheers

J

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:7 (5 by maintainers)

github_iconTop GitHub Comments

4reactions
logaretmcommented, Oct 26, 2018

Here is a small example to address your issue:

https://jsfiddle.net/logaretm/vxg5ydm2/11/

The lists and the model that tracks which is selected is not the same, this is because v-validate directive does not work properly with v-for loops which is a limitation for using directives in Vue (directive does not have access to the loop context). Our rule is very simple, it just checks if the value passed has a minimum length of x. It is considered pure.

Validation isn’t invoked manually, it is indeed invoked whenever the user interacts with the input, for checkboxes the default event is change. The validate or validateAll are only used on form submission to ensure inputs were not manipulated in other ways, for example, I can just open the dev tools and manipulate the input value without emitting events or even updating the v-model (all the more reason to have server-side validation). VeeValidate knows how to resolve the current values for those inputs (they are bound by a directive after all), so it can reliably validate them without having you to pass the values.

Here is an example that is using your approach, even with the v-for limitation:

https://jsfiddle.net/logaretm/t81d32ec/6/

Notice that we added the continues modifier since the required and atLeastOne rules are basically equivalent, so we would like to forcibly use our validator even if the field isn’t required. The modifier is documented here.

0reactions
sts-ryan-holtoncommented, Apr 7, 2021

How can we acheive this in Vee Validate 3, it appears that the continues modifier has gone, and there’s no atLeastOne rule. My current markup that I need to try and apply this to is:

<validation-observer v-slot="{ handleSubmit }">
  <form @submit.stop.prevent="handleSubmit(submitForm)">

    <!-- Step 1 -->
    <validation-observer v-if="editor.step == 1" :key="1">
      // inputs
    </validation-observer>

    <!-- Step 2: Choose Sources -->
    <validation-observer v-if="editor.step == 2" :key="2">
      <ul v-for="(source, table, sourceIndex) in editor.sources" :key="sourceIndex" class="mb-3">
        <li>

          <!-- Data Source (Table) -->
          <validation-provider
            name="data source"
            :rules="{ required: { allowFalse: false } }"
            v-slot="{ errors, classes }"
          >
            <label :for="'source-'+sourceIndex" class="font-medium text-gray-700 cursor-pointer block p-4 border rounded-md">
              <div class="flex">
                <div class="flex-1">
                  <p class="text-xs font-medium text-gray-400">Data Source</p>
                  <h5 class="text-sm font-bold text-gray-500" :class="source.isChecked ? 'text-indigo-600' : ''">{{ table }}</h5>
                </div>
                <div v-if="source.isChecked" class="flex-1 items-center flex justify-end" :class="source.isChecked ? 'text-indigo-600' : ''">
                  <svg xmlns="http://www.w3.org/2000/svg" fill="none" height="24" width="24" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                </div>
              </div>
              <input :id="'source-'+sourceIndex" v-model="source.isChecked" type="checkbox" class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded cursor-pointer hidden">
            </label>
            <span class="text-xs text-red-500">{{ errors[0] }}</span>
          </validation-provider>

        </li>
      </ul>
    </validation-observer>

  </form>
</validation-observer>
Read more comments on GitHub >

github_iconTop Results From Across the Web

Making sure at least one checkbox is checked - Stack Overflow
Here's a non-jQuery solution to check if any checkboxes on the page are checked. var checkboxes = document.querySelectorAll('input[type=" ...
Read more >
At least one checkbox must be selected (checked) - Tech Notes
There is a form with multiple checkboxes and we're going to make sure that at least one is checked using pure JavaScript. To...
Read more >
Form Validation: Require at Least One Checkbox Before Submit
This is a simple way to force a user to make a selection from a fieldset of checkboxes in order to submit a...
Read more >
How to Check Atleast One Checkbox is Checked or Not in ...
This post will give you simple example of jquery validate at least one checkbox checked. Here, i will give you very simple example...
Read more >
Only submit if at least one checkbox is checked - artlung lab
The idea is that at least one check box should be checked. I have an onSubmit for the form and a JS function...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found