Skip to content

Commit

Permalink
Add Typanion Resolver (#189)
Browse files Browse the repository at this point in the history
  • Loading branch information
stramel authored Jul 31, 2021
1 parent 4769398 commit 2678ad4
Show file tree
Hide file tree
Showing 13 changed files with 459 additions and 5 deletions.
43 changes: 41 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -377,8 +377,7 @@ import Schema, { number, string } from 'computed-types';

const schema = Schema({
username: string.min(1).error('username field is required'),
password: string.min(1).error('password field is required'),
password: number,
age: number,
});

const App = () => {
Expand All @@ -404,6 +403,46 @@ const App = () => {
export default App;
```

### [typanion](https://github.com/arcanis/typanion)

Static and runtime type assertion library with no dependencies

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

```tsx
import React from 'react';
import { useForm } from 'react-hook-form';
import { typanionResolver } from '@hookform/resolvers/typanion';
import * as t from 'typanion';

const isUser = t.isObject({
username: t.applyCascade(t.isString(), [t.hasMinLength(1)]),
age: t.applyCascade(t.isNumber(), [t.isInteger(), t.isInInclusiveRange(1, 100)]),
});

const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: typanionResolver(isUser),
});

return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
{errors.name?.message && <p>{errors.name?.message}</p>}
<input type="number" {...register('age')} />
{errors.age?.message && <p>{errors.age?.message}</p>}
<input type="submit" />
</form>
);
};

export default App;
```

## Backers

Thanks goes to all our backers! [[Become a backer](https://opencollective.com/react-hook-form#backer)].
Expand Down
1 change: 1 addition & 0 deletions config/node-13-exports.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const subRepositories = [
'io-ts',
'nope',
'computed-types',
'typanion'
];

const copySrc = () => {
Expand Down
18 changes: 15 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "@hookform/resolvers",
"amdName": "hookformResolvers",
"version": "1.3.1",
"description": "React Hook Form validation resolvers: Yup, Joi, Superstruct, Zod, Vest, Class Validator, io-ts, Nope and computed-types",
"description": "React Hook Form validation resolvers: Yup, Joi, Superstruct, Zod, Vest, Class Validator, io-ts, Nope, computed-types and Typanion",
"main": "dist/resolvers.js",
"module": "dist/resolvers.module.js",
"umd:main": "dist/resolvers.umd.js",
Expand Down Expand Up @@ -69,6 +69,12 @@
"import": "./computed-types/dist/computed-types.mjs",
"require": "./computed-types/dist/computed-types.js"
},
"./typanion": {
"browser": "./typanion/dist/typanion.module.js",
"umd": "./typanion/dist/typanion.umd.js",
"import": "./typanion/dist/typanion.mjs",
"require": "./typanion/dist/typanion.js"
},
"./package.json": "./package.json",
"./": "./"
},
Expand Down Expand Up @@ -100,7 +106,10 @@
"nope/dist",
"computed-types/package.json",
"computed-types/src",
"computed-types/dist"
"computed-types/dist",
"typanion/package.json",
"typanion/src",
"typanion/dist"
],
"publishConfig": {
"access": "public"
Expand All @@ -118,6 +127,7 @@
"build:class-validator": "microbundle --cwd class-validator --globals '@hookform/resolvers=hookformResolvers'",
"build:nope": "microbundle --cwd nope --globals '@hookform/resolvers=hookformResolvers'",
"build:computed-types": "microbundle --cwd computed-types --globals '@hookform/resolvers=hookformResolvers'",
"build:typanion": "microbundle --cwd typanion --globals '@hookform/resolvers=hookformResolvers'",
"postbuild": "node ./config/node-13-exports.js",
"lint": "eslint . --ext .ts,.js --ignore-path .gitignore",
"lint:types": "tsc",
Expand All @@ -140,7 +150,8 @@
"class-validator",
"io-ts",
"nope",
"computed-types"
"computed-types",
"typanion"
],
"repository": {
"type": "git",
Expand Down Expand Up @@ -185,6 +196,7 @@
"reflect-metadata": "^0.1.13",
"superstruct": "^0.15.2",
"ts-jest": "^27.0.1",
"typanion": "^3.3.2",
"typescript": "^4.3.2",
"vest": "^3.2.3",
"yup": "^0.32.9",
Expand Down
18 changes: 18 additions & 0 deletions typanion/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "typanion",
"amdName": "hookformResolversTypanion",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: typanion",
"main": "dist/typanion.js",
"module": "dist/typanion.module.js",
"umd:main": "dist/typanion.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",
"typanion": "^3.3.2"
}
}
88 changes: 88 additions & 0 deletions typanion/src/__tests__/Form-native-validation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import React from 'react';
import { render, screen, act } from '@testing-library/react';
import user from '@testing-library/user-event';
import { useForm } from 'react-hook-form';
import * as t from 'typanion';
import { typanionResolver } from '..';

const ERROR_MESSAGE = 'Expected to have a length of at least 1 elements (got 0)';

const schema = t.isObject({
username: t.applyCascade(t.isString(), [t.hasMinLength(1)]),
password: t.applyCascade(t.isString(), [t.hasMinLength(1)]),
});

interface FormData {
unusedProperty: string;
username: string;
password: string;
}

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

function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: typanionResolver(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 Typanion", async () => {
const handleSubmit = jest.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 act(async () => {
user.click(screen.getByText(/submit/i));
});

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

// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(ERROR_MESSAGE);

await act(async () => {
user.type(screen.getByPlaceholderText(/username/i), 'joe');
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('');
});
57 changes: 57 additions & 0 deletions typanion/src/__tests__/Form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import React from 'react';
import { render, screen, act } from '@testing-library/react';
import user from '@testing-library/user-event';
import { useForm } from 'react-hook-form';
import * as t from 'typanion';
import { typanionResolver } from '..';

const schema = t.isObject({
username: t.applyCascade(t.isString(), [t.hasMinLength(1)]),
password: t.applyCascade(t.isString(), [t.hasMinLength(1)]),
});

interface FormData {
unusedProperty: string;
username: string;
password: string;
}

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

function TestComponent({ onSubmit }: Props) {
const {
register,
formState: { errors },
handleSubmit,
} = useForm<FormData>({
resolver: typanionResolver(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 Typanion and TypeScript's integration", async () => {
const handleSubmit = jest.fn();
render(<TestComponent onSubmit={handleSubmit} />);

expect(screen.queryAllByRole(/alert/i)).toHaveLength(0);

await act(async () => {
user.click(screen.getByText(/submit/i));
});

expect(screen.getAllByText('Expected to have a length of at least 1 elements (got 0)')).toHaveLength(2);
expect(handleSubmit).not.toHaveBeenCalled();
});
77 changes: 77 additions & 0 deletions typanion/src/__tests__/__fixtures__/data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { Field, InternalFieldName } from 'react-hook-form';
import * as t from 'typanion';



export const isSchema = t.isObject({
username: t.applyCascade(t.isString(), [
t.matchesRegExp(/^\w+$/),
t.hasMinLength(2),
t.hasMaxLength(30),
]),
password: t.applyCascade(t.isString(), [
t.matchesRegExp(new RegExp('.*[A-Z].*')), // one uppercase character
t.matchesRegExp(new RegExp('.*[a-z].*')), // one lowercase character
t.matchesRegExp(new RegExp('.*\\d.*')), // one number
t.matchesRegExp(new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*')), // one special character
t.hasMinLength(8), // Must be at least 8 characters in length
]),
repeatPassword: t.applyCascade(t.isString(), [
t.matchesRegExp(new RegExp('.*[A-Z].*')), // one uppercase character
t.matchesRegExp(new RegExp('.*[a-z].*')), // one lowercase character
t.matchesRegExp(new RegExp('.*\\d.*')), // one number
t.matchesRegExp(new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*')), // one special character
t.hasMinLength(8), // Must be at least 8 characters in length
]),
accessToken: t.isString(),
birthYear: t.applyCascade(t.isNumber(), [t.isInteger(), t.isInInclusiveRange(1900, 2013)]),
email: t.applyCascade(t.isString(), [t.matchesRegExp(/^\S+@\S+$/)]),
tags: t.isArray(t.isString()),
enabled: t.isBoolean(),
like: t.isObject({
id: t.applyCascade(t.isNumber(), [t.isInteger(), t.isPositive()]),
name: t.applyCascade(t.isString(), [t.hasMinLength(4)])
}),
});

export const validData = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
birthYear: 2000,
email: '[email protected]',
tags: ['tag1', 'tag2'],
enabled: true,
accessToken: 'accessToken',
like: {
id: 1,
name: 'name',
},
};

export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: { id: 'z' },
tags: [1, 2, 3],
};

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',
},
};
Loading

0 comments on commit 2678ad4

Please sign in to comment.