(form: FormikContextType<TFormValues>, error?: unknown)
| 35 | |
| 36 | export const getFormHelpers = |
| 37 | <TFormValues>(form: FormikContextType<TFormValues>, error?: unknown) => |
| 38 | (fieldName: string, options: GetFormHelperOptions = {}): FormHelpers => { |
| 39 | const { |
| 40 | backendFieldName, |
| 41 | helperText: defaultHelperText, |
| 42 | maxLength, |
| 43 | } = options; |
| 44 | let helperText = defaultHelperText; |
| 45 | const apiValidationErrors = isApiValidationError(error) |
| 46 | ? (mapApiErrorToFieldErrors( |
| 47 | error.response.data, |
| 48 | ) as FormikErrors<TFormValues> & { [key: string]: string }) |
| 49 | : undefined; |
| 50 | // Since the fieldName can be a path string like parameters[0].value we need to use getIn |
| 51 | const touched = Boolean(getIn(form.touched, fieldName.toString())); |
| 52 | const formError = getIn(form.errors, fieldName.toString()); |
| 53 | // Since the field in the form can be different from the backend, we need to |
| 54 | // check for both when getting the error |
| 55 | const apiField = backendFieldName ?? fieldName; |
| 56 | const apiError = apiValidationErrors?.[apiField.toString()]; |
| 57 | |
| 58 | const fieldProps = form.getFieldProps(fieldName); |
| 59 | const value = fieldProps.value; |
| 60 | |
| 61 | let lengthError: ReactNode = null; |
| 62 | // Show a message if the input is approaching or over the maximum length. |
| 63 | if ( |
| 64 | maxLength && |
| 65 | maxLength > 0 && |
| 66 | typeof value === "string" && |
| 67 | value.length > maxLength - 30 |
| 68 | ) { |
| 69 | helperText = `This cannot be longer than ${maxLength} characters. (${value.length}/${maxLength})`; |
| 70 | // Show it as an error, rather than a hint |
| 71 | if (value.length > maxLength) { |
| 72 | lengthError = helperText; |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | // API and regular validation errors should wait to be shown, but length errors should |
| 77 | // be more responsive. |
| 78 | const errorToDisplay = |
| 79 | (touched && apiError) || lengthError || (touched && formError); |
| 80 | |
| 81 | return { |
| 82 | ...fieldProps, |
| 83 | id: fieldName.toString(), |
| 84 | error: Boolean(errorToDisplay), |
| 85 | helperText: errorToDisplay || helperText, |
| 86 | }; |
| 87 | }; |
| 88 | |
| 89 | export const onChangeTrimmed = |
| 90 | <T>(form: FormikContextType<T>, callback?: (value: string) => void) => |
no test coverage detected