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

feat: add support for custom error messages for required fields #687

Open
wants to merge 6 commits into
base: master
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
75 changes: 71 additions & 4 deletions ajv/src/__tests__/Form-native-validation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { useForm } from 'react-hook-form';
import { ajvResolver } from '..';

const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const CUSTOM_USERNAME_REQUIRED_MESSAGE = 'Username is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';

type FormData = { username: string; password: string };
Expand All @@ -26,23 +27,41 @@ const schema: JSONSchemaType<FormData> = {
},
required: ['username', 'password'],
additionalProperties: false,
errorMessage: {
required: {
username: CUSTOM_USERNAME_REQUIRED_MESSAGE,
},
},
};

interface Props {
onSubmit: (data: FormData) => void;
isInitialValueUndefined?: boolean;
}

function TestComponent({ onSubmit }: Props) {
function TestComponent({ onSubmit, isInitialValueUndefined }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: ajvResolver(schema),
shouldUseNativeValidation: true,
});

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />

<input {...register('password')} placeholder="password" />
<input
{...register('username', {
setValueAs: (value) =>
isInitialValueUndefined ? value || undefined : value,
})}
placeholder="username"
/>

<input
{...register('password', {
setValueAs: (value) =>
isInitialValueUndefined ? value || undefined : value,
})}
placeholder="password"
/>

<button type="submit">submit</button>
</form>
Expand Down Expand Up @@ -92,3 +111,51 @@ test("form's native validation with Ajv", async () => {
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});

test("form's native validation with Ajv for required fields with custom error messages", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} isInitialValueUndefined />);

// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');

// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');

await user.click(screen.getByText(/submit/i));

// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe(
CUSTOM_USERNAME_REQUIRED_MESSAGE,
);

// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(
"must have required property 'password'",
);

await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');

// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');

// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});
37 changes: 34 additions & 3 deletions ajv/src/__tests__/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,19 @@ const schema: JSONSchemaType<FormData> = {
},
required: ['username', 'password'],
additionalProperties: false,
errorMessage: {
required: {
username: 'Username is required',
},
},
};

interface Props {
onSubmit: (data: FormData) => void;
isInitialValueUndefined?: boolean;
}

function TestComponent({ onSubmit }: Props) {
function TestComponent({ onSubmit, isInitialValueUndefined }: Props) {
const {
register,
formState: { errors },
Expand All @@ -40,10 +46,20 @@ function TestComponent({ onSubmit }: Props) {

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
<input
{...register('username', {
setValueAs: (value) =>
isInitialValueUndefined ? value || undefined : value,
})}
/>
{errors.username && <span role="alert">{errors.username.message}</span>}

<input {...register('password')} />
<input
{...register('password', {
setValueAs: (value) =>
isInitialValueUndefined ? value || undefined : value,
})}
/>
{errors.password && <span role="alert">{errors.password.message}</span>}

<button type="submit">submit</button>
Expand All @@ -63,3 +79,18 @@ test("form's validation with Ajv and TypeScript's integration", async () => {
expect(screen.getByText(/password field is required/i)).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

test("form's validation with Ajv and TypeScript's integration for required fields with custom error messages", async () => {
const handleSubmit = vi.fn();
render(<TestComponent isInitialValueUndefined onSubmit={handleSubmit} />);

expect(screen.queryAllByRole('alert')).toHaveLength(0);

await user.click(screen.getByText(/submit/i));

expect(screen.getByText(/Username is required/i)).toBeInTheDocument();
expect(
screen.getByText(/must have required property 'password'/i),
).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});
58 changes: 58 additions & 0 deletions ajv/src/__tests__/__fixtures__/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,53 @@ export const schema: JSONSchemaType<Data> = {
additionalProperties: false,
};

export const errorMessageSchema: JSONSchemaType<Data> = {
type: 'object',
properties: {
username: {
type: 'string',
minLength: 3,
},
password: {
type: 'string',
pattern: '.*[A-Z].*',
errorMessage: {
pattern: 'One uppercase character',
},
},
deepObject: {
type: 'object',
properties: {
data: { type: 'string' },
twoLayersDeep: {
type: 'object',
properties: { name: { type: 'string' } },
additionalProperties: false,
required: ['name'],
errorMessage: {
required: {
name: 'Name is required',
},
},
},
},
required: ['data', 'twoLayersDeep'],
errorMessage: {
required: {
data: 'Data is required',
},
},
},
},
required: ['username', 'password', 'deepObject'],
additionalProperties: false,
errorMessage: {
required: {
password: 'Password is required',
},
},
};

export const validData: Data = {
username: 'jsun969',
password: 'validPassword',
Expand Down Expand Up @@ -70,6 +117,17 @@ export const invalidDataWithUndefined = {
},
};

export const invalidDataWithAllUndefined = {
username: undefined,
password: undefined,
deepObject: {
twoLayersDeep: {
name: undefined,
},
data: undefined,
},
};

export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
Expand Down
58 changes: 58 additions & 0 deletions ajv/src/__tests__/__snapshots__/ajv.ts.snap
Original file line number Diff line number Diff line change
@@ -1,5 +1,63 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`ajvResolver > should return all the custom and native error messages from ajvResolver when properties are undefined and result will keep the input data structure 1`] = `
{
"errors": {
"deepObject": {
"data": {
"message": "Data is required",
"ref": undefined,
"type": "errorMessage",
},
"twoLayersDeep": {
"name": {
"message": "Name is required",
"ref": undefined,
"type": "errorMessage",
},
},
},
"password": {
"message": "Password is required",
"ref": {
"name": "password",
},
"type": "errorMessage",
},
"username": {
"message": "must have required property 'username'",
"ref": {
"name": "username",
},
"type": "required",
},
},
"values": {},
}
`;

exports[`ajvResolver > should return all the custom error messages from ajvResolver when some property is undefined and result will keep the input data structure 1`] = `
{
"errors": {
"deepObject": {
"data": {
"message": "Data is required",
"ref": undefined,
"type": "errorMessage",
},
},
"password": {
"message": "Password is required",
"ref": {
"name": "password",
},
"type": "errorMessage",
},
},
"values": {},
}
`;

exports[`ajvResolver > should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true 1`] = `
{
"errors": {
Expand Down
36 changes: 35 additions & 1 deletion ajv/src/__tests__/ajv.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { ajvResolver } from '..';
import { fields, invalidData, invalidDataWithUndefined, schema, validData } from './__fixtures__/data';
import {
fields,
invalidData,
invalidDataWithUndefined,
schema,
validData,
errorMessageSchema,
invalidDataWithAllUndefined,
} from './__fixtures__/data';

const shouldUseNativeValidation = false;

Expand Down Expand Up @@ -94,4 +102,30 @@ describe('ajvResolver', () => {
),
).toMatchSnapshot();
});

it('should return all the custom error messages from ajvResolver when some property is undefined and result will keep the input data structure', async () => {
expect(
await ajvResolver(errorMessageSchema, undefined, { mode: 'sync' })(
invalidDataWithUndefined,
undefined,
{
fields,
shouldUseNativeValidation,
},
),
).toMatchSnapshot();
});

it('should return all the custom and native error messages from ajvResolver when properties are undefined and result will keep the input data structure', async () => {
expect(
await ajvResolver(errorMessageSchema, undefined, { mode: 'sync' })(
invalidDataWithAllUndefined,
undefined,
{
fields,
shouldUseNativeValidation,
},
),
).toMatchSnapshot();
});
});
Loading