Skip to content

Commit

Permalink
feat: improve formControl to display all errors on onSubmit mode (#100)
Browse files Browse the repository at this point in the history
  • Loading branch information
aguilaj authored Aug 20, 2024
1 parent 32c6f07 commit 3ccbd9d
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 10 deletions.
67 changes: 59 additions & 8 deletions src/components/Form.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
FormLabel,
FormGuideline,
InputGroup,
Button,
} from '@cap-collectif/ui'
import { Meta } from '@storybook/react'
import { useForm } from 'react-hook-form'
Expand Down Expand Up @@ -250,14 +251,7 @@ export const Default = () => {

<FormControl name="dateHour" control={control} isRequired>
<FormLabel label="Date With Hour" />
<FieldInput
type="dateHour"
name="dateHour"
control={control}
dateInputProps={{
isOutsideRange: true,
}}
/>
<FieldInput type="dateHour" name="dateHour" control={control} />
</FormControl>

<FormControl name="color" control={control} isRequired>
Expand Down Expand Up @@ -311,3 +305,60 @@ export const Focus = () => {
</Box>
)
}

export const TriggerAllErrorsOnSubmit = () => {
const { control, handleSubmit, formState } = useForm({
mode: 'onSubmit',
})

const { errors, isValid } = formState

const onSubmit = (data: any) => {
console.log(data)
}

return (
<Box
as="form"
maxWidth="40%"
margin="auto"
noValidate
onSubmit={handleSubmit(onSubmit)}
>
<FormControl name="firstName" control={control} isRequired>
<FormLabel label="Firstname" />
<FieldInput
type="text"
minLength={4}
name="firstName"
control={control}
/>
</FormControl>
<FormControl name="lastName" control={control} isRequired>
<FormLabel label="lastName" />
<FieldInput
type="text"
minLength={4}
name="lastName"
control={control}
/>
</FormControl>
<FormControl name="condition" control={control} isRequired>
<FormLabel label="condition" />
<FieldInput
id="condition"
type="checkbox"
name="condition"
control={control}
placeholder="Jean"
/>
</FormControl>

<Button mb={4} type="submit">
Submit
</Button>
<pre>{JSON.stringify({ isValid }, null, 2)}</pre>
<pre>{JSON.stringify({ errors }, null, 2)}</pre>
</Box>
)
}
8 changes: 6 additions & 2 deletions src/components/FormControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,12 @@ export const FormControl: FC<FormControlProps> = ({
: undefined,
},
})
const isInvalid = invalid && getTouchedState(touchedFields, name)

const mode = control?._options?.mode

const isInvalid =
invalid &&
(mode === 'onChange' ? getTouchedState(touchedFields, name) : true)

const errorFieldId = `${name}-error`

Expand All @@ -75,7 +80,6 @@ export const FormControl: FC<FormControlProps> = ({
mb={4}
isInvalid={isInvalid}
isRequired={isRequired}
toto="toto"
sx={{
'&:last-child': {
mb: 0,
Expand Down

0 comments on commit 3ccbd9d

Please sign in to comment.