Skip to content

Commit

Permalink
feat(arktype): add arktype resolver (#542)
Browse files Browse the repository at this point in the history
* feat(arktype): add arktype resolver

* chore: add arktype

* test: update

* chore(deps): update

* docs: add summary
  • Loading branch information
jorisre committed Apr 15, 2023
1 parent 4a65f85 commit d2d6fec
Show file tree
Hide file tree
Showing 14 changed files with 1,827 additions and 1,257 deletions.
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,21 @@

- [React-hook-form validation resolver documentation ](https://react-hook-form.com/api/useform/#resolver)

### Supported resolvers

- [Yup](#Yup)
- [Zod](#Zod)
- [Superstruct](#Superstruct)
- [Joi](#Joi)
- [Class Validator](#Class-Validator)
- [io-ts](#io-ts)
- [Nope](#Nope)
- [computed-types](#computed-types)
- [typanion](#typanion)
- [Ajv](#Ajv)
- [TypeBox](#TypeBox)
- [ArkType](#ArkType)

## API

```
Expand Down Expand Up @@ -486,6 +501,37 @@ const App = () => {
};
```

### [ArkType](https://github.com/arktypeio/arktype)

TypeScript's 1:1 validator, optimized from editor to runtime

[![npm](https://img.shields.io/bundlephobia/minzip/arktype?style=for-the-badge)](https://bundlephobia.com/result?p=arktype)

```typescript jsx
import { useForm } from 'react-hook-form';
import { arktypeResolver } from '@hookform/resolvers/arktype';
import { type } from 'arktype';

const schema = type({
username: 'string>1',
password: 'string>1',
});

const App = () => {
const { register, handleSubmit } = useForm({
resolver: arktypeResolver(schema),
});

return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```

## Backers

Thanks goes to all our backers! [[Become a backer](https://opencollective.com/react-hook-form#backer)].
Expand Down
17 changes: 17 additions & 0 deletions arktype/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "@hookform/resolvers/arktype",
"amdName": "hookformResolversArktype",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: arktype",
"main": "dist/arktype.js",
"module": "dist/arktype.module.js",
"umd:main": "dist/arktype.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": "^7.0.0",
"@hookform/resolvers": "^2.0.0"
}
}
82 changes: 82 additions & 0 deletions arktype/src/__tests__/Form-native-validation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import React from 'react';
import { useForm } from 'react-hook-form';
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { arktypeResolver } from '..';
import { type } from 'arktype';

const schema = type({
username: 'string>1',
password: 'string>1',
});

type FormData = typeof schema.infer;

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

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

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

<input {...register('password')} placeholder="password" />

<button type="submit">submit</button>
</form>
);
}

test("form's native validation with Zod", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);

// 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(
'username must be more than 1 characters (was 0)',
);

// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(
'password must be more than 1 characters (was 0)',
);

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('');
});
56 changes: 56 additions & 0 deletions arktype/src/__tests__/Form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { useForm } from 'react-hook-form';
import { arktypeResolver } from '..';
import { type } from 'arktype';

const schema = type({
username: 'string>1',
password: 'string>1',
});

type FormData = typeof schema.infer & { unusedProperty: string };

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

function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormData>({
resolver: arktypeResolver(schema), // Useful to check TypeScript regressions
});

return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}

<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}

<button type="submit">submit</button>
</form>
);
}

test("form's validation with arkType and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);

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

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

expect(
screen.getByText('username must be more than 1 characters (was 0)'),
).toBeInTheDocument();
expect(
screen.getByText('password must be more than 1 characters (was 0)'),
).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});
67 changes: 67 additions & 0 deletions arktype/src/__tests__/__fixtures__/data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { Field, InternalFieldName } from 'react-hook-form';
import { type, arrayOf, union } from 'arktype';

export const schema = type({
username: 'string>2',
password: union(['string>8', '&', '/.*[A-Za-z].*/'], ['/.*\\d.*/']),
repeatPassword: 'string>1',
accessToken: union('string', 'number'),
birthYear: '1900<number<2013',
email: 'email',
tags: arrayOf('string'),
enabled: 'boolean',
url: 'string>1',
'like?': arrayOf(
type({
id: 'number',
name: 'string>3',
}),
),
dateStr: 'Date',
});

export const validData: typeof schema.infer = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
accessToken: 'accessToken',
url: 'https://react-hook-form.com/',
like: [
{
id: 1,
name: 'name',
},
],
dateStr: new Date('2020-01-01'),
};

export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
url: 'abc',
};

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

exports[`arktypeResolver > should return a single error from arktypeResolver when validation fails 1`] = `
{
"errors": {
"accessToken": {
"message": "accessToken must be defined",
"ref": undefined,
"type": "missing",
},
"birthYear": {
"message": "birthYear must be a number (was string)",
"ref": undefined,
"type": "domain",
},
"dateStr": {
"message": "dateStr must be defined",
"ref": undefined,
"type": "missing",
},
"email": {
"message": "email must be a valid email (was '')",
"ref": {
"name": "email",
},
"type": "regex",
},
"enabled": {
"message": "enabled must be defined",
"ref": undefined,
"type": "missing",
},
"like": [
{
"id": {
"message": "like/0/id must be a number (was string)",
"ref": undefined,
"type": "domain",
},
"name": {
"message": "like/0/name must be defined",
"ref": undefined,
"type": "missing",
},
},
],
"password": {
"message": "At password, '___' must be...
more than 8 characters
a string matching /.*[A-Za-z].*/",
"ref": {
"name": "password",
},
"type": "multi",
},
"repeatPassword": {
"message": "repeatPassword must be defined",
"ref": undefined,
"type": "missing",
},
"tags": {
"message": "tags must be defined",
"ref": undefined,
"type": "missing",
},
"username": {
"message": "username must be defined",
"ref": {
"name": "username",
},
"type": "missing",
},
},
"values": {},
}
`;
26 changes: 26 additions & 0 deletions arktype/src/__tests__/arktype.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { arktypeResolver } from '..';
import { schema, validData, invalidData, fields } from './__fixtures__/data';

const shouldUseNativeValidation = false;

describe('arktypeResolver', () => {
it('should return values from arktypeResolver when validation pass & raw=true', async () => {
const result = await arktypeResolver(schema, undefined, {
raw: true,
})(validData, undefined, {
fields,
shouldUseNativeValidation,
});

expect(result).toEqual({ errors: {}, values: validData });
});

it('should return a single error from arktypeResolver when validation fails', async () => {
const result = await arktypeResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});

expect(result).toMatchSnapshot();
});
});

0 comments on commit d2d6fec

Please sign in to comment.