mobx-react-form icon indicating copy to clipboard operation
mobx-react-form copied to clipboard

Validate at lease one checkbox checked

Open Leapfrognz opened this issue 6 years ago • 2 comments

Hi, I was wondering how to setup validation so that at least one checkbox in a group needs to be checked. Would I use nested fields for this?

        name: 'group',
        label: 'Group',
        fields: [{
            name: 'option1',
            label: 'option 1',
            type: 'checkbox',
        }, {
            name: 'option2',
            label: 'option 2',
            type: 'checkbox',
        }, {
            name: 'option3',
            label: 'option 3',
            type: 'checkbox',
        }],

Any help appreciated

Leapfrognz avatar Jul 20 '18 11:07 Leapfrognz

I'd suggest looking into one or more of the following:

  • Custom JS Validators: https://foxhound87.github.io/mobx-react-form/docs/validation/modes/vjf-custom.html
  • onChange/onToggle Hooks: https://foxhound87.github.io/mobx-react-form/docs/events/event-handlers.html
  • observe/intercept: https://foxhound87.github.io/mobx-react-form/docs/extra/mobx-events.html

pdfowler avatar Jul 28 '18 01:07 pdfowler

I used the observers object to validate one field when a different field changes.

An alternative is doing it in onSubmit. inside the function, get access to the form object, do your validations, and if it's invalid you can call form.invalidate('At least one checkbox must be selected')

Dakkers avatar Dec 06 '18 17:12 Dakkers