How to validate multiple checkboxes

Say I have an object like this:

this.inputs = [
  {  value: 1, text: '1', checked: false },
  {  value: 2, text: '2', checked: false }
  {  value: 3, text: '3', checked: false }
]

And add it the my view like this.

<div repeat.for="input of inputs">
  <input type="checkbox" id="checkbox-${$index}"
    checked.bind="input.checked" change.trigger="onChange()">
  <label for="checkbox-${$index}">
    ${input.text}
  </label>
</div>

How do I validate the aurelia way?

Here I am creating a rule, that should check if at least one of the entries in the inputs array is checked.

validationRules
      .on(this)
      .ensure('inputs')
      .satisfies(() => this.inputs.some(input => input.checked))

How do I use the & validate binding behaviour here?

In my onChange function I can call this:

const result = await this.validator.validate()

But it seems like my rule is just being ignored.

Hi Ivan,

You were close. But, the issue appears to most likely be caused by the lack of validate in your HTML. Notice on the checked.bind attribute I’ve added in the validate binding behaviour.

<div repeat.for="input of inputs">
  <input type="checkbox" id="checkbox-${$index}"
    checked.bind="input.checked & validate" change.trigger="onChange()">
  <label for="checkbox-${$index}">
    ${input.text}
  </label>
</div>

If this doesn’t sort out the issue, let me know.

Thank for the reply Dwayne. Unfortunately adding checked.bind="input.checked & validate" does not seem to be changing things.

I managed to get it working. Not sure if this is the proper way or just a hack.

Instead of defining the rule like this:

validationRules
      .on(this)
      .ensure('inputs')
      .satisfies(() => this.inputs.some(input => input.checked))

I changed it to this:

this.inputs.forEach(input => {
      validationRules
        .on(input)
        .ensure('checked')
        .satisfies(() => this.inputs.some(d => d.checked === true))
    })

And also added checked.bind="input.checked & validate to the html as @dwaynecharrington suggested.

Glad that you have found a working solution.

Here is another approach that depends on encapsulating the parts that depend on the collection to a different CE, and applying the validate BB on the binding of that CE. This keeps the validation rules simpler.

Here is an SB project to demonstrate that.

2 Likes