cchapman
cchapman

Reputation: 3367

How to add Validation for multiple checkboxes in Aurelia?

So I've just got a form set up with a list checkboxes of states so that you can select multiple states, however I'm not quite sure how to put the validation on the collection of checkboxes rather than each individual one.

Right now, I have:

my-view.html

    <div repeat.for="territory of availableTerritories" class="form-row">
        <input type="checkbox" value.bind="territory" checked.bind="region.territories & validate">
        <label>${territory}</label>
    </div>

    <ul if.bind="validationController.errors">
        <li repeat.for="error of validationController.errors">
            ${error.message}
        </li>
    </ul>
    <button class="button cancel" click.trigger="cancel()">Cancel</button>
    <button class="button ok" click.trigger="saveRegion()">Save Territories</button>

my-viewmodel.js

availableTerritories = [
'US-AL',
'US-AK',
...
]

region = {
    territories: []
}

constructor(validationController) {
    ValidationRules
        .ensure(region=>region.territories)
            .required()
            .minItems(1)
            .on(this.region);
}

However, when I test this out with an empty input, I get a ValidationError for every checkbox rather than just the collection of them.

My ValidationError message

  • Territories must contain at least 1 item.
  • Territories must contain at least 1 item.
  • Territories must contain at least 1 item.
  • ...

Upvotes: 1

Views: 630

Answers (1)

cchapman
cchapman

Reputation: 3367

So I ended up adding a hidden input to the form and doing the validation on that, instead of the checkboxes themselves:

my-view.html

<div repeat.for="territory of availableTerritories" class="form-row">
    <input type="checkbox" value.bind="territory" checked.bind="region.territories">    // No validation here
    <label>${territory}</label>
</div>

<input type="hidden" value.bind="region.territories & validate">    //Added validation here instead

<ul if.bind="validationController.errors">
    <li repeat.for="error of validationController.errors">
        ${error.message}
    </li>
</ul>
<button class="button cancel" click.trigger="cancel()">Cancel</button>
<button class="button ok" click.trigger="saveRegion()">Save Territories</button>

Upvotes: 1

Related Questions