MCPcopy Index your code
hub / github.com/coder/coder / getFormHelpers

Function getFormHelpers

site/src/utils/formUtils.ts:37–87  ·  view source on GitHub ↗
(form: FormikContextType<TFormValues>, error?: unknown)

Source from the content-addressed store, hash-verified

35
36export 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
89export const onChangeTrimmed =
90 <T>(form: FormikContextType<T>, callback?: (value: string) => void) =>

Callers 15

PortForwardPopoverViewFunction · 0.90
ExampleFormFunction · 0.90
formUtils.test.tsFile · 0.90
FormFunction · 0.90
UpdateGroupFormFunction · 0.90
CreateGroupPageViewFunction · 0.90
ProviderFormFunction · 0.90
EditUserFormFunction · 0.90
CreateUserFormFunction · 0.90
PasswordSignInFormFunction · 0.90

Calls 2

isApiValidationErrorFunction · 0.90
mapApiErrorToFieldErrorsFunction · 0.90

Tested by

no test coverage detected