Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement min choices validation #206

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,9 @@ export const MultiChoice = ({ index, question }: QuestionProps) => {
}

const choices = [...question.choices]
// Put can abstain on a separated variable to avoid typing errors on validation function
// Put can abstain and minChoices on a separated variable to avoid typing errors on validation function
const canAbstain = election.resultsType.properties.canAbstain
const minChoices = election.resultsType?.properties?.numChoices?.min

return (
<Stack sx={styles.stack}>
Expand All @@ -91,6 +92,16 @@ export const MultiChoice = ({ index, question }: QuestionProps) => {
// allow a single selection if is an abstain
if (canAbstain && v && v.length < election.voteType.maxCount!) return true

// If there are min choices, validate that the user has selected at least that amount
if (minChoices) {
if (v && v.length >= minChoices && v.length <= election.voteType.maxCount) {
return true
}
if (minChoices === 1) return localize('validation.at_least_one')
return localize('validation.min_choices_count', { count: minChoices })
}

// If no minChoices configured, selected choices must be the maxCount
return (
(v && v.length === election.voteType.maxCount) ||
localize('validation.choices_count', { count: election.voteType.maxCount })
Expand Down Expand Up @@ -123,6 +134,7 @@ export const MultiChoice = ({ index, question }: QuestionProps) => {
if (maxSelected) return
onChange([...values, e.target.value])
}

trigger(index) // Manually trigger validation
}}
>
Expand Down
1 change: 1 addition & 0 deletions packages/chakra-components/src/i18n/locales.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ export const locales = {
required: 'This field is required',
min_length: 'This field must be at least {{ min }} characters long',
choices_count: 'Select {{ count }} choices',
min_choices_count: 'Select minimum of {{ count }} choices',
at_least_one: 'You must select at least one option',
},
// questions and vote button
Expand Down
Loading