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

[@mantine/form] validate-field-value: parent path validation #3080

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/mantine-form/src/validate/validate-field-value.test.ts
Expand Up @@ -29,6 +29,16 @@ describe('@mantine/form/validate-field-value', () => {
).toStrictEqual({ hasError: true, error: 'error-b' });
});

it('validates parent of nested field with rules record', () => {
expect(
validateFieldValue(
'a',
{ a: { b: (value) => (value === 1 ? 'error-b' : null) } },
{ a: [{ b: 2 }, { b: 1 }] }
)
).toStrictEqual({ hasError: true, error: 'error-b' });
});

it('validates array field with rules record', () => {
expect(
validateFieldValue(
Expand Down
6 changes: 4 additions & 2 deletions src/mantine-form/src/validate/validate-field-value.ts
Expand Up @@ -11,6 +11,8 @@ export function validateFieldValue<T>(
}

const results = validateValues(rules, values);
const hasError = path in results.errors;
return { hasError, error: hasError ? results.errors[path] : null };
const pathInError = Object.keys(results.errors).find((errorKey) =>
path.split('.').every((pathPart, i) => pathPart === errorKey.split('.')[i])
);
return { hasError: !!pathInError, error: pathInError ? results.errors[pathInError] : null };
}