Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optionally show multiple validation errors per field #1573

Open
wants to merge 1 commit into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 24 additions & 6 deletions src/Formik.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
FormikProps,
FieldMetaProps,
FieldInputProps,
ValidationSchemaOptions,
} from './types';
import {
isFunction,
Expand Down Expand Up @@ -122,6 +123,7 @@ function useFormikInternal<Values = object>({
isInitialValid,
enableReinitialize = false,
onSubmit,
validationSchemaOptions = { showMultipleFieldErrors: false },
...rest
}: FormikConfig<Values>) {
const props = { validateOnChange, validateOnBlur, onSubmit, ...rest };
Expand Down Expand Up @@ -202,12 +204,12 @@ function useFormikInternal<Values = object>({
resolve(emptyErrors);
},
(err: any) => {
resolve(yupToFormErrors(err));
resolve(yupToFormErrors(err, validationSchemaOptions));
}
);
});
},
[props.validationSchema]
[props.validationSchema, validationSchemaOptions]
);

const runSingleFieldLevelValidation = React.useCallback(
Expand Down Expand Up @@ -837,14 +839,30 @@ function warnAboutMissingIdentifier({
/**
* Transform Yup ValidationError to a more usable object
*/
export function yupToFormErrors<Values>(yupError: any): FormikErrors<Values> {
export function yupToFormErrors<Values>(
yupError: any,
validationSchemaOptions: ValidationSchemaOptions
): FormikErrors<Values> {
let errors: FormikErrors<Values> = {};
if (yupError.inner.length === 0) {
return setIn(errors, yupError.path, yupError.message);
}
for (let err of yupError.inner) {
if (!(errors as any)[err.path]) {
errors = setIn(errors, err.path, err.message);
// if showMultipleFieldErrors is enabled, set the error value
// to an array of all errors for that field
if (validationSchemaOptions.showMultipleFieldErrors) {
for (let err of yupError.inner) {
let fieldErrors = getIn(errors, err.path);
if (!fieldErrors) {
fieldErrors = [];
}
fieldErrors.push(err.message);
errors = setIn(errors, err.path, fieldErrors);
}
} else {
for (let err of yupError.inner) {
if (!(errors as any)[err.path]) {
errors = setIn(errors, err.path, err.message);
}
}
}
return errors;
Expand Down
10 changes: 9 additions & 1 deletion src/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,10 @@ export interface FormikConfig<Values> extends FormikSharedConfig {
* A Yup Schema or a function that returns a Yup schema
*/
validationSchema?: any | (() => any);
/**
* Additional options relating to validationSchema
*/
validationSchemaOptions?: ValidationSchemaOptions;

/**
* Validation function. Must return an error object or promise that
Expand All @@ -199,6 +203,10 @@ export interface FormikConfig<Values> extends FormikSharedConfig {
validate?: (values: Values) => void | object | Promise<FormikErrors<Values>>;
}

export interface ValidationSchemaOptions {
showMultipleFieldErrors?: boolean;
}

/**
* State, handlers, and helpers made available to form component or render prop
* of <Formik/>.
Expand Down Expand Up @@ -252,7 +260,7 @@ export interface FieldMetaProps<Value> {
/** Value of the field */
value: Value;
/** Error message of the field */
error?: string;
error?: string | string[];
/** Has the field been visited? */
touched: boolean;
/** Initial value of the field */
Expand Down
17 changes: 17 additions & 0 deletions test/Formik.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1091,4 +1091,21 @@ describe('<Formik>', () => {
users: [{ firstName: 'required', lastName: 'required' }],
});
});

it('respects the validationSchemaOptions prop', async () => {
const validationSchema = Yup.object().shape({
firstName: Yup.string().required('required'),
});

const { getProps } = renderFormik({
initialValues: { users: [{ firstName: '' }] },
validationSchema,
validationSchemaOptions: { showMultipleFieldErrors: true },
});

await getProps().validateForm();
expect(getProps().errors).toEqual({
firstName: ['required'],
});
});
});
16 changes: 15 additions & 1 deletion test/yupHelpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import { validateYupSchema, yupToFormErrors } from '../src';
const Yup = require('yup');
const schema = Yup.object().shape({
name: Yup.string('Name must be a string').required('required'),
num: Yup.number()
.min(1, 'must be greater than or equal to 1')
.integer('must be an integer'),
});

describe('Yup helpers', () => {
Expand All @@ -11,11 +14,22 @@ describe('Yup helpers', () => {
try {
await schema.validate({}, { abortEarly: false });
} catch (e) {
expect(yupToFormErrors(e)).toEqual({
expect(yupToFormErrors(e, { showMultipleFieldErrors: false })).toEqual({
name: 'required',
});
}
});

it('should return an array for each field when showMultipleFieldErrors is enabled', async () => {
try {
await schema.validate({ name: '', num: 0.1 }, { abortEarly: false });
} catch (e) {
expect(yupToFormErrors(e, { showMultipleFieldErrors: true })).toEqual({
name: ['required'],
num: ['must be greater than or equal to 1', 'must be an integer'],
});
}
});
});

describe('validateYupSchema()', () => {
Expand Down