Skip to content

Commit

Permalink
Implement min choices validation
Browse files Browse the repository at this point in the history
  • Loading branch information
selankon committed Nov 6, 2024
1 parent 97fa626 commit e3d7ca9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
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,15 @@ 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
}
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 +133,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

0 comments on commit e3d7ca9

Please sign in to comment.