-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Feat: getValidators() function for react-hook-form
- Loading branch information
1 parent
4442f03
commit 5682921
Showing
5 changed files
with
48 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { PublicQuestion } from '@/types/form' | ||
import { RegisterOptions } from 'react-hook-form' | ||
|
||
export const getValidators = ( | ||
field: PublicQuestion, | ||
t: any | ||
): RegisterOptions => { | ||
const validators: RegisterOptions = {} | ||
|
||
// If field is required, set required validation rule | ||
if (field.required) { | ||
validators.required = t('required') | ||
} | ||
|
||
// If validators exist on the meta, loop through this | ||
if (field.meta?.validators) { | ||
field.meta.validators.forEach( | ||
(validatorRule: string | [string, number]) => { | ||
if (typeof validatorRule === 'string') { | ||
// Handle single validator 'required' | ||
if (validatorRule === 'required') { | ||
validators.required = field.required ? t('required') : false | ||
} | ||
} else if (Array.isArray(validatorRule)) { | ||
// Handle validators with parameters like ['maxLength', 100] | ||
const [validatorName, validatorValue] = validatorRule | ||
|
||
if (validatorName === 'maxLength') { | ||
validators.maxLength = { | ||
value: validatorValue, | ||
message: t('max_length', { maxLength: validatorValue }), | ||
} | ||
} | ||
} | ||
} | ||
) | ||
} | ||
|
||
return validators | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters