build revisions and layout updates for toast
This commit is contained in:
parent
b341a3675e
commit
39235193e6
1116 changed files with 130517 additions and 12 deletions
21
node_modules/@hookform/resolvers/LICENSE
generated
vendored
Normal file
21
node_modules/@hookform/resolvers/LICENSE
generated
vendored
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2019-present Beier(Bill) Luo
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
927
node_modules/@hookform/resolvers/README.md
generated
vendored
Normal file
927
node_modules/@hookform/resolvers/README.md
generated
vendored
Normal file
|
|
@ -0,0 +1,927 @@
|
|||
<div align="center">
|
||||
<p align="center">
|
||||
<a href="https://react-hook-form.com" title="React Hook Form - Simple React forms validation">
|
||||
<img src="https://raw.githubusercontent.com/bluebill1049/react-hook-form/master/docs/logo.png" alt="React Hook Form Logo - React hook custom hook for form validation" />
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p align="center">Performant, flexible and extensible forms with easy to use validation.</p>
|
||||
|
||||
<div align="center">
|
||||
|
||||
[](https://www.npmjs.com/package/@hookform/resolvers)
|
||||
[](https://www.npmjs.com/package/@hookform/resolvers)
|
||||
[](https://bundlephobia.com/result?p=@hookform/resolvers)
|
||||
|
||||
</div>
|
||||
|
||||
## React Hook Form Resolvers
|
||||
|
||||
This function allows you to use any external validation library such as Yup, Zod, Joi, Vest, Ajv and many others. The goal is to make sure you can seamlessly integrate whichever validation library you prefer. If you're not using a library, you can always write your own logic to validate your forms.
|
||||
|
||||
## Install
|
||||
|
||||
Install your preferred validation library alongside `@hookform/resolvers`.
|
||||
|
||||
npm install @hookform/resolvers # npm
|
||||
yarn add @hookform/resolvers # yarn
|
||||
pnpm install @hookform/resolvers # pnpm
|
||||
bun install @hookform/resolvers # bun
|
||||
|
||||
<details>
|
||||
<summary>Resolver Comparison</summary>
|
||||
|
||||
| resolver | Infer values <br /> from schema | [criteriaMode](https://react-hook-form.com/docs/useform#criteriaMode) |
|
||||
|---|---|---|
|
||||
| AJV | ❌ | `firstError \| all` |
|
||||
| Arktype | ✅ | `firstError` |
|
||||
| class-validator | ✅ | `firstError \| all` |
|
||||
| computed-types | ✅ | `firstError` |
|
||||
| Effect | ✅ | `firstError \| all` |
|
||||
| fluentvalidation-ts | ❌ | `firstError` |
|
||||
| io-ts | ✅ | `firstError` |
|
||||
| joi | ❌ | `firstError \| all` |
|
||||
| Nope | ❌ | `firstError` |
|
||||
| Standard Schema | ✅ | `firstError \| all` |
|
||||
| Superstruct | ✅ | `firstError` |
|
||||
| typanion | ✅ | `firstError` |
|
||||
| typebox | ✅ | `firstError \| all` |
|
||||
| typeschema | ❌ | `firstError \| all` |
|
||||
| valibot | ✅ | `firstError \| all` |
|
||||
| vest | ❌ | `firstError \| all` |
|
||||
| vine | ✅ | `firstError \| all` |
|
||||
| yup | ✅ | `firstError \| all` |
|
||||
| zod | ✅ | `firstError \| all` |
|
||||
</details>
|
||||
|
||||
## TypeScript
|
||||
|
||||
Most of the resolvers can infer the output type from the schema. See comparison table for more details.
|
||||
|
||||
```tsx
|
||||
useForm<Input, Context, Output>()
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```tsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod'; // or 'zod/v4'
|
||||
|
||||
const schema = z.object({
|
||||
id: z.number(),
|
||||
});
|
||||
|
||||
// Automatically infers the output type from the schema
|
||||
useForm({
|
||||
resolver: zodResolver(schema),
|
||||
});
|
||||
|
||||
// Force the output type
|
||||
useForm<z.input<typeof schema>, any, z.output<typeof schema>>({
|
||||
resolver: zodResolver(schema),
|
||||
});
|
||||
```
|
||||
|
||||
## Links
|
||||
|
||||
- [React-hook-form validation resolver documentation ](https://react-hook-form.com/docs/useform#resolver)
|
||||
|
||||
### Supported resolvers
|
||||
|
||||
- [React Hook Form Resolvers](#react-hook-form-resolvers)
|
||||
- [Install](#install)
|
||||
- [TypeScript](#typescript)
|
||||
- [Links](#links)
|
||||
- [Supported resolvers](#supported-resolvers)
|
||||
- [API](#api)
|
||||
- [Quickstart](#quickstart)
|
||||
- [Yup](#yup)
|
||||
- [Zod](#zod)
|
||||
- [Superstruct](#superstruct)
|
||||
- [Joi](#joi)
|
||||
- [Vest](#vest)
|
||||
- [Class Validator](#class-validator)
|
||||
- [io-ts](#io-ts)
|
||||
- [Nope](#nope)
|
||||
- [computed-types](#computed-types)
|
||||
- [typanion](#typanion)
|
||||
- [Ajv](#ajv)
|
||||
- [TypeBox](#typebox)
|
||||
- [With `ValueCheck`](#with-valuecheck)
|
||||
- [With `TypeCompiler`](#with-typecompiler)
|
||||
- [ArkType](#arktype)
|
||||
- [Valibot](#valibot)
|
||||
- [TypeSchema](#typeschema)
|
||||
- [effect-ts](#effect-ts)
|
||||
- [VineJS](#vinejs)
|
||||
- [fluentvalidation-ts](#fluentvalidation-ts)
|
||||
- [standard-schema](#standard-schema)
|
||||
- [Backers](#backers)
|
||||
- [Contributors](#contributors)
|
||||
|
||||
## API
|
||||
|
||||
```
|
||||
type Options = {
|
||||
mode: 'async' | 'sync',
|
||||
raw?: boolean
|
||||
}
|
||||
|
||||
resolver(schema: object, schemaOptions?: object, resolverOptions: Options)
|
||||
```
|
||||
|
||||
| | type | Required | Description |
|
||||
| --------------- | -------- | -------- | --------------------------------------------- |
|
||||
| schema | `object` | ✓ | validation schema |
|
||||
| schemaOptions | `object` | | validation library schema options |
|
||||
| resolverOptions | `object` | | resolver options, `async` is the default mode |
|
||||
|
||||
## Quickstart
|
||||
|
||||
### [Yup](https://github.com/jquense/yup)
|
||||
|
||||
Dead simple Object schema validation.
|
||||
|
||||
[](https://bundlephobia.com/result?p=yup)
|
||||
|
||||
```typescript jsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import * as yup from 'yup';
|
||||
|
||||
const schema = yup
|
||||
.object()
|
||||
.shape({
|
||||
name: yup.string().required(),
|
||||
age: yup.number().required(),
|
||||
})
|
||||
.required();
|
||||
|
||||
const App = () => {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: yupResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<input {...register('name')} />
|
||||
<input type="number" {...register('age')} />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [Zod](https://github.com/colinhacks/zod)
|
||||
|
||||
TypeScript-first schema validation with static type inference
|
||||
|
||||
[](https://bundlephobia.com/result?p=zod)
|
||||
|
||||
> ⚠️ Example below uses the `valueAsNumber`, which requires `react-hook-form` v6.12.0 (released Nov 28, 2020) or later.
|
||||
|
||||
```tsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod'; // or 'zod/v4'
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().min(1, { message: 'Required' }),
|
||||
age: z.number().min(10),
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm({
|
||||
resolver: zodResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<input {...register('name')} />
|
||||
{errors.name?.message && <p>{errors.name?.message}</p>}
|
||||
<input type="number" {...register('age', { valueAsNumber: true })} />
|
||||
{errors.age?.message && <p>{errors.age?.message}</p>}
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [Superstruct](https://github.com/ianstormtaylor/superstruct)
|
||||
|
||||
A simple and composable way to validate data in JavaScript (or TypeScript).
|
||||
|
||||
[](https://bundlephobia.com/result?p=superstruct)
|
||||
|
||||
```typescript jsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { superstructResolver } from '@hookform/resolvers/superstruct';
|
||||
import { object, string, number } from 'superstruct';
|
||||
|
||||
const schema = object({
|
||||
name: string(),
|
||||
age: number(),
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: superstructResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<input {...register('name')} />
|
||||
<input type="number" {...register('age', { valueAsNumber: true })} />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [Joi](https://github.com/sideway/joi)
|
||||
|
||||
The most powerful data validation library for JS.
|
||||
|
||||
[](https://bundlephobia.com/result?p=joi)
|
||||
|
||||
```typescript jsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { joiResolver } from '@hookform/resolvers/joi';
|
||||
import Joi from 'joi';
|
||||
|
||||
const schema = Joi.object({
|
||||
name: Joi.string().required(),
|
||||
age: Joi.number().required(),
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: joiResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<input {...register('name')} />
|
||||
<input type="number" {...register('age')} />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [Vest](https://github.com/ealush/vest)
|
||||
|
||||
Vest 🦺 Declarative Validation Testing.
|
||||
|
||||
[](https://bundlephobia.com/result?p=vest)
|
||||
|
||||
```typescript jsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { vestResolver } from '@hookform/resolvers/vest';
|
||||
import { create, test, enforce } from 'vest';
|
||||
|
||||
const validationSuite = create((data = {}) => {
|
||||
test('username', 'Username is required', () => {
|
||||
enforce(data.username).isNotEmpty();
|
||||
});
|
||||
|
||||
test('password', 'Password is required', () => {
|
||||
enforce(data.password).isNotEmpty();
|
||||
});
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
const { register, handleSubmit, errors } = useForm({
|
||||
resolver: vestResolver(validationSuite),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((data) => console.log(data))}>
|
||||
<input {...register('username')} />
|
||||
<input type="password" {...register('password')} />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [Class Validator](https://github.com/typestack/class-validator)
|
||||
|
||||
Decorator-based property validation for classes.
|
||||
|
||||
[](https://bundlephobia.com/result?p=class-validator)
|
||||
|
||||
> ⚠️ Remember to add these options to your `tsconfig.json`!
|
||||
|
||||
```
|
||||
"strictPropertyInitialization": false,
|
||||
"experimentalDecorators": true
|
||||
```
|
||||
|
||||
```tsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { classValidatorResolver } from '@hookform/resolvers/class-validator';
|
||||
import { Length, Min, IsEmail } from 'class-validator';
|
||||
|
||||
class User {
|
||||
@Length(2, 30)
|
||||
username: string;
|
||||
|
||||
@IsEmail()
|
||||
email: string;
|
||||
}
|
||||
|
||||
const resolver = classValidatorResolver(User);
|
||||
|
||||
const App = () => {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<User>({ resolver });
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((data) => console.log(data))}>
|
||||
<input type="text" {...register('username')} />
|
||||
{errors.username && <span>{errors.username.message}</span>}
|
||||
<input type="text" {...register('email')} />
|
||||
{errors.email && <span>{errors.email.message}</span>}
|
||||
<input type="submit" value="Submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [io-ts](https://github.com/gcanti/io-ts)
|
||||
|
||||
Validate your data with powerful decoders.
|
||||
|
||||
[](https://bundlephobia.com/result?p=io-ts)
|
||||
|
||||
```typescript jsx
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { ioTsResolver } from '@hookform/resolvers/io-ts';
|
||||
import t from 'io-ts';
|
||||
// you don't have to use io-ts-types, but it's very useful
|
||||
import tt from 'io-ts-types';
|
||||
|
||||
const schema = t.type({
|
||||
username: t.string,
|
||||
age: tt.NumberFromString,
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: ioTsResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<input {...register('username')} />
|
||||
<input type="number" {...register('age')} />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
export default App;
|
||||
```
|
||||
|
||||
### [Nope](https://github.com/bvego/nope-validator)
|
||||
|
||||
A small, simple, and fast JS validator
|
||||
|
||||
[](https://bundlephobia.com/result?p=nope-validator)
|
||||
|
||||
```typescript jsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { nopeResolver } from '@hookform/resolvers/nope';
|
||||
import Nope from 'nope-validator';
|
||||
|
||||
const schema = Nope.object().shape({
|
||||
name: Nope.string().required(),
|
||||
age: Nope.number().required(),
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: nopeResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<input {...register('name')} />
|
||||
<input type="number" {...register('age')} />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [computed-types](https://github.com/neuledge/computed-types)
|
||||
|
||||
TypeScript-first schema validation with static type inference
|
||||
|
||||
[](https://bundlephobia.com/result?p=computed-types)
|
||||
|
||||
```tsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { computedTypesResolver } from '@hookform/resolvers/computed-types';
|
||||
import Schema, { number, string } from 'computed-types';
|
||||
|
||||
const schema = Schema({
|
||||
username: string.min(1).error('username field is required'),
|
||||
age: number,
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm({
|
||||
resolver: computedTypesResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<input {...register('name')} />
|
||||
{errors.name?.message && <p>{errors.name?.message}</p>}
|
||||
<input type="number" {...register('age', { valueAsNumber: true })} />
|
||||
{errors.age?.message && <p>{errors.age?.message}</p>}
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [typanion](https://github.com/arcanis/typanion)
|
||||
|
||||
Static and runtime type assertion library with no dependencies
|
||||
|
||||
[](https://bundlephobia.com/result?p=typanion)
|
||||
|
||||
```tsx
|
||||
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>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [Ajv](https://github.com/ajv-validator/ajv)
|
||||
|
||||
The fastest JSON validator for Node.js and browser
|
||||
|
||||
[](https://bundlephobia.com/result?p=ajv)
|
||||
|
||||
```tsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { ajvResolver } from '@hookform/resolvers/ajv';
|
||||
|
||||
// must use `minLength: 1` to implement required field
|
||||
const schema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
username: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
errorMessage: { minLength: 'username field is required' },
|
||||
},
|
||||
password: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
errorMessage: { minLength: 'password field is required' },
|
||||
},
|
||||
},
|
||||
required: ['username', 'password'],
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
const App = () => {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm({
|
||||
resolver: ajvResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((data) => console.log(data))}>
|
||||
<input {...register('username')} />
|
||||
{errors.username && <span>{errors.username.message}</span>}
|
||||
<input {...register('password')} />
|
||||
{errors.password && <span>{errors.password.message}</span>}
|
||||
<button type="submit">submit</button>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [TypeBox](https://github.com/sinclairzx81/typebox)
|
||||
|
||||
JSON Schema Type Builder with Static Type Resolution for TypeScript
|
||||
|
||||
[](https://bundlephobia.com/result?p=@sinclair/typebox)
|
||||
|
||||
#### With `ValueCheck`
|
||||
|
||||
```typescript jsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { typeboxResolver } from '@hookform/resolvers/typebox';
|
||||
import { Type } from '@sinclair/typebox';
|
||||
|
||||
const schema = Type.Object({
|
||||
username: Type.String({ minLength: 1 }),
|
||||
password: Type.String({ minLength: 1 }),
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: typeboxResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<input {...register('username')} />
|
||||
<input type="password" {...register('password')} />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
#### With `TypeCompiler`
|
||||
|
||||
A high-performance JIT of `TypeBox`, [read more](https://github.com/sinclairzx81/typebox#typecompiler)
|
||||
|
||||
```typescript jsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { typeboxResolver } from '@hookform/resolvers/typebox';
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { TypeCompiler } from '@sinclair/typebox/compiler';
|
||||
|
||||
const schema = Type.Object({
|
||||
username: Type.String({ minLength: 1 }),
|
||||
password: Type.String({ minLength: 1 }),
|
||||
});
|
||||
|
||||
const typecheck = TypeCompiler.Compile(schema);
|
||||
|
||||
const App = () => {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: typeboxResolver(typecheck),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<input {...register('username')} />
|
||||
<input type="password" {...register('password')} />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [ArkType](https://github.com/arktypeio/arktype)
|
||||
|
||||
TypeScript's 1:1 validator, optimized from editor to runtime
|
||||
|
||||
[](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>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [Valibot](https://github.com/fabian-hiller/valibot)
|
||||
|
||||
The modular and type safe schema library for validating structural data
|
||||
|
||||
[](https://bundlephobia.com/result?p=valibot)
|
||||
|
||||
```typescript jsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { valibotResolver } from '@hookform/resolvers/valibot';
|
||||
import * as v from 'valibot';
|
||||
|
||||
const schema = v.object({
|
||||
username: v.pipe(
|
||||
v.string('username is required'),
|
||||
v.minLength(3, 'Needs to be at least 3 characters'),
|
||||
v.endsWith('cool', 'Needs to end with `cool`'),
|
||||
),
|
||||
password: v.string('password is required'),
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: valibotResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<input {...register('username')} />
|
||||
<input type="password" {...register('password')} />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [TypeSchema](https://typeschema.com)
|
||||
|
||||
Universal adapter for schema validation, compatible with [any validation library](https://typeschema.com/#coverage)
|
||||
|
||||
[](https://bundlephobia.com/result?p=@typeschema/main)
|
||||
|
||||
```typescript jsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { typeschemaResolver } from '@hookform/resolvers/typeschema';
|
||||
import { z } from 'zod';
|
||||
|
||||
// Use your favorite validation library
|
||||
const schema = z.object({
|
||||
username: z.string().min(1, { message: 'Required' }),
|
||||
password: z.number().min(1, { message: 'Required' }),
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: typeschemaResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<input {...register('username')} />
|
||||
<input type="password" {...register('password')} />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [effect-ts](https://github.com/Effect-TS/effect)
|
||||
|
||||
A powerful TypeScript framework that provides a fully-fledged functional effect system with a rich standard library.
|
||||
|
||||
[](https://bundlephobia.com/result?p=effect)
|
||||
|
||||
```typescript jsx
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { effectTsResolver } from '@hookform/resolvers/effect-ts';
|
||||
import { Schema } from 'effect';
|
||||
|
||||
const schema = Schema.Struct({
|
||||
username: Schema.String.pipe(
|
||||
Schema.nonEmptyString({ message: () => 'username required' }),
|
||||
),
|
||||
password: Schema.String.pipe(
|
||||
Schema.nonEmptyString({ message: () => 'password required' }),
|
||||
),
|
||||
});
|
||||
|
||||
type FormData = typeof schema.Type;
|
||||
|
||||
interface Props {
|
||||
onSubmit: (data: FormData) => void;
|
||||
}
|
||||
|
||||
function TestComponent({ onSubmit }: Props) {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
// provide generic if TS has issues inferring types
|
||||
} = useForm<FormData>({
|
||||
resolver: effectTsResolver(schema),
|
||||
});
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### [VineJS](https://github.com/vinejs/vine)
|
||||
|
||||
VineJS is a form data validation library for Node.js
|
||||
|
||||
[](https://bundlephobia.com/result?p=@vinejs/vine)
|
||||
|
||||
```typescript jsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { vineResolver } from '@hookform/resolvers/vine';
|
||||
import vine from '@vinejs/vine';
|
||||
|
||||
const schema = vine.compile(
|
||||
vine.object({
|
||||
username: vine.string().minLength(1),
|
||||
password: vine.string().minLength(1),
|
||||
}),
|
||||
);
|
||||
|
||||
const App = () => {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: vineResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<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>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
### [fluentvalidation-ts](https://github.com/AlexJPotter/fluentvalidation-ts)
|
||||
|
||||
A TypeScript-first library for building strongly-typed validation rules
|
||||
|
||||
[](https://bundlephobia.com/result?p=@vinejs/vine)
|
||||
|
||||
```typescript jsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { fluentValidationResolver } from '@hookform/resolvers/fluentvalidation-ts';
|
||||
import { Validator } from 'fluentvalidation-ts';
|
||||
|
||||
class FormDataValidator extends Validator<FormData> {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.ruleFor('username')
|
||||
.notEmpty()
|
||||
.withMessage('username is a required field');
|
||||
this.ruleFor('password')
|
||||
.notEmpty()
|
||||
.withMessage('password is a required field');
|
||||
}
|
||||
}
|
||||
|
||||
const App = () => {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: fluentValidationResolver(new FormDataValidator()),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<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>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
### [standard-schema](https://github.com/standard-schema/standard-schema)
|
||||
|
||||
A standard interface for TypeScript schema validation libraries
|
||||
|
||||
[](https://bundlephobia.com/result?p=@standard-schema/spec)
|
||||
|
||||
Example zod
|
||||
|
||||
```typescript jsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { standardSchemaResolver } from '@hookform/resolvers/standard-schema';
|
||||
import { z } from 'zod';
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().min(1, { message: 'Required' }),
|
||||
age: z.number().min(10),
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm({
|
||||
resolver: standardSchemaResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<input {...register('name')} />
|
||||
{errors.name?.message && <p>{errors.name?.message}</p>}
|
||||
<input type="number" {...register('age', { valueAsNumber: true })} />
|
||||
{errors.age?.message && <p>{errors.age?.message}</p>}
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
Example arkType
|
||||
|
||||
```typescript jsx
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { standardSchemaResolver } from '@hookform/resolvers/standard-schema';
|
||||
import { type } from 'arktype';
|
||||
|
||||
const schema = type({
|
||||
username: 'string>1',
|
||||
password: 'string>1',
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: standardSchemaResolver(schema),
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
||||
<input {...register('username')} />
|
||||
<input type="password" {...register('password')} />
|
||||
<input type="submit" />
|
||||
</form>
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
## Backers
|
||||
|
||||
Thanks go to all our backers! [[Become a backer](https://opencollective.com/react-hook-form#backer)].
|
||||
|
||||
<a href="https://opencollective.com/react-hook-form#backers">
|
||||
<img src="https://opencollective.com/react-hook-form/backers.svg?width=950" />
|
||||
</a>
|
||||
|
||||
## Contributors
|
||||
|
||||
Thanks go to these wonderful people! [[Become a contributor](CONTRIBUTING.md)].
|
||||
|
||||
<a href="https://github.com/react-hook-form/react-hook-form/graphs/contributors">
|
||||
<img src="https://opencollective.com/react-hook-form/contributors.svg?width=950" />
|
||||
</a>
|
||||
22
node_modules/@hookform/resolvers/ajv/dist/ajv.d.ts
generated
vendored
Normal file
22
node_modules/@hookform/resolvers/ajv/dist/ajv.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { Resolver } from './types';
|
||||
/**
|
||||
* Creates a resolver for react-hook-form using Ajv schema validation
|
||||
* @param {Schema} schema - The Ajv schema to validate against
|
||||
* @param {Object} schemaOptions - Additional schema validation options
|
||||
* @param {Object} resolverOptions - Additional resolver configuration
|
||||
* @param {string} [resolverOptions.mode='async'] - Validation mode
|
||||
* @returns {Resolver<Schema>} A resolver function compatible with react-hook-form
|
||||
* @example
|
||||
* const schema = ajv.compile({
|
||||
* type: 'object',
|
||||
* properties: {
|
||||
* name: { type: 'string' },
|
||||
* age: { type: 'number' }
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* useForm({
|
||||
* resolver: ajvResolver(schema)
|
||||
* });
|
||||
*/
|
||||
export declare const ajvResolver: Resolver;
|
||||
2
node_modules/@hookform/resolvers/ajv/dist/ajv.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/ajv/dist/ajv.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
var e=require("@hookform/resolvers"),r=require("ajv"),a=require("ajv-errors"),s=require("ajv-formats"),o=require("react-hook-form");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=/*#__PURE__*/t(r),n=/*#__PURE__*/t(a),u=/*#__PURE__*/t(s),c=function(e,r){for(var a={},s=function(e){"required"===e.keyword&&(e.instancePath+="/"+e.params.missingProperty);var s=e.instancePath.substring(1).replace(/\//g,".");if(a[s]||(a[s]={message:e.message,type:e.keyword}),r){var t=a[s].types,i=t&&t[e.keyword];a[s]=o.appendErrors(s,r,a,e.keyword,i?[].concat(i,e.message||""):e.message)}},t=function(){var r=e[i];"errorMessage"===r.keyword?r.params.errors.forEach(function(e){e.message=r.message,s(e)}):s(r)},i=0;i<e.length;i+=1)t();return a};exports.ajvResolver=function(r,a,s){return void 0===s&&(s={}),function(o,t,l){try{var v=new i.default(Object.assign({},{allErrors:!0,validateSchema:!0},a));n.default(v),u.default(v);var d=v.compile(Object.assign({$async:s&&"async"===s.mode},r)),f=d(o);return l.shouldUseNativeValidation&&e.validateFieldsNatively({},l),Promise.resolve(f?{values:o,errors:{}}:{values:{},errors:e.toNestErrors(c(d.errors,!l.shouldUseNativeValidation&&"all"===l.criteriaMode),l)})}catch(e){return Promise.reject(e)}}};
|
||||
//# sourceMappingURL=ajv.js.map
|
||||
1
node_modules/@hookform/resolvers/ajv/dist/ajv.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/ajv/dist/ajv.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
2
node_modules/@hookform/resolvers/ajv/dist/ajv.mjs
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/ajv/dist/ajv.mjs
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import o from"ajv";import a from"ajv-errors";import s from"ajv-formats";import{appendErrors as t}from"react-hook-form";var i=function(r,e){for(var o={},a=function(r){"required"===r.keyword&&(r.instancePath+="/"+r.params.missingProperty);var a=r.instancePath.substring(1).replace(/\//g,".");if(o[a]||(o[a]={message:r.message,type:r.keyword}),e){var s=o[a].types,i=s&&s[r.keyword];o[a]=t(a,e,o,r.keyword,i?[].concat(i,r.message||""):r.message)}},s=function(){var e=r[i];"errorMessage"===e.keyword?e.params.errors.forEach(function(r){r.message=e.message,a(r)}):a(e)},i=0;i<r.length;i+=1)s();return o},n=function(t,n,m){return void 0===m&&(m={}),function(c,v,f){try{var l=new o(Object.assign({},{allErrors:!0,validateSchema:!0},n));a(l),s(l);var u=l.compile(Object.assign({$async:m&&"async"===m.mode},t)),d=u(c);return f.shouldUseNativeValidation&&r({},f),Promise.resolve(d?{values:c,errors:{}}:{values:{},errors:e(i(u.errors,!f.shouldUseNativeValidation&&"all"===f.criteriaMode),f)})}catch(r){return Promise.reject(r)}}};export{n as ajvResolver};
|
||||
//# sourceMappingURL=ajv.module.js.map
|
||||
2
node_modules/@hookform/resolvers/ajv/dist/ajv.modern.mjs
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/ajv/dist/ajv.modern.mjs
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import s from"ajv";import o from"ajv-errors";import a from"ajv-formats";import{appendErrors as t}from"react-hook-form";const m=(r,e)=>{const s={},o=r=>{"required"===r.keyword&&(r.instancePath+=`/${r.params.missingProperty}`);const o=r.instancePath.substring(1).replace(/\//g,".");if(s[o]||(s[o]={message:r.message,type:r.keyword}),e){const a=s[o].types,m=a&&a[r.keyword];s[o]=t(o,e,s,r.keyword,m?[].concat(m,r.message||""):r.message)}};for(let e=0;e<r.length;e+=1){const s=r[e];"errorMessage"===s.keyword?s.params.errors.forEach(r=>{r.message=s.message,o(r)}):o(s)}return s},n=(t,n,i={})=>async(c,l,d)=>{const g=new s(Object.assign({},{allErrors:!0,validateSchema:!0},n));o(g),a(g);const p=g.compile(Object.assign({$async:i&&"async"===i.mode},t)),f=p(c);return d.shouldUseNativeValidation&&r({},d),f?{values:c,errors:{}}:{values:{},errors:e(m(p.errors,!d.shouldUseNativeValidation&&"all"===d.criteriaMode),d)}};export{n as ajvResolver};
|
||||
//# sourceMappingURL=ajv.modern.mjs.map
|
||||
1
node_modules/@hookform/resolvers/ajv/dist/ajv.modern.mjs.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/ajv/dist/ajv.modern.mjs.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
2
node_modules/@hookform/resolvers/ajv/dist/ajv.module.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/ajv/dist/ajv.module.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import o from"ajv";import a from"ajv-errors";import s from"ajv-formats";import{appendErrors as t}from"react-hook-form";var i=function(r,e){for(var o={},a=function(r){"required"===r.keyword&&(r.instancePath+="/"+r.params.missingProperty);var a=r.instancePath.substring(1).replace(/\//g,".");if(o[a]||(o[a]={message:r.message,type:r.keyword}),e){var s=o[a].types,i=s&&s[r.keyword];o[a]=t(a,e,o,r.keyword,i?[].concat(i,r.message||""):r.message)}},s=function(){var e=r[i];"errorMessage"===e.keyword?e.params.errors.forEach(function(r){r.message=e.message,a(r)}):a(e)},i=0;i<r.length;i+=1)s();return o},n=function(t,n,m){return void 0===m&&(m={}),function(c,v,f){try{var l=new o(Object.assign({},{allErrors:!0,validateSchema:!0},n));a(l),s(l);var u=l.compile(Object.assign({$async:m&&"async"===m.mode},t)),d=u(c);return f.shouldUseNativeValidation&&r({},f),Promise.resolve(d?{values:c,errors:{}}:{values:{},errors:e(i(u.errors,!f.shouldUseNativeValidation&&"all"===f.criteriaMode),f)})}catch(r){return Promise.reject(r)}}};export{n as ajvResolver};
|
||||
//# sourceMappingURL=ajv.module.js.map
|
||||
1
node_modules/@hookform/resolvers/ajv/dist/ajv.module.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/ajv/dist/ajv.module.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
2
node_modules/@hookform/resolvers/ajv/dist/ajv.umd.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/ajv/dist/ajv.umd.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("ajv"),require("ajv-errors"),require("ajv-formats"),require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","ajv","ajv-errors","ajv-formats","react-hook-form"],r):r((e||self).hookformResolversAjv={},e.hookformResolvers,e.ajv,e.ajvErrors,e.ajvFormats,e.ReactHookForm)}(this,function(e,r,o,a,s,t){function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=/*#__PURE__*/i(o),f=/*#__PURE__*/i(a),l=/*#__PURE__*/i(s),u=function(e,r){for(var o={},a=function(e){"required"===e.keyword&&(e.instancePath+="/"+e.params.missingProperty);var a=e.instancePath.substring(1).replace(/\//g,".");if(o[a]||(o[a]={message:e.message,type:e.keyword}),r){var s=o[a].types,i=s&&s[e.keyword];o[a]=t.appendErrors(a,r,o,e.keyword,i?[].concat(i,e.message||""):e.message)}},s=function(){var r=e[i];"errorMessage"===r.keyword?r.params.errors.forEach(function(e){e.message=r.message,a(e)}):a(r)},i=0;i<e.length;i+=1)s();return o};e.ajvResolver=function(e,o,a){return void 0===a&&(a={}),function(s,t,i){try{var v=new n.default(Object.assign({},{allErrors:!0,validateSchema:!0},o));f.default(v),l.default(v);var c=v.compile(Object.assign({$async:a&&"async"===a.mode},e)),d=c(s);return i.shouldUseNativeValidation&&r.validateFieldsNatively({},i),Promise.resolve(d?{values:s,errors:{}}:{values:{},errors:r.toNestErrors(u(c.errors,!i.shouldUseNativeValidation&&"all"===i.criteriaMode),i)})}catch(e){return Promise.reject(e)}}}});
|
||||
//# sourceMappingURL=ajv.umd.js.map
|
||||
1
node_modules/@hookform/resolvers/ajv/dist/ajv.umd.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/ajv/dist/ajv.umd.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
2
node_modules/@hookform/resolvers/ajv/dist/index.d.ts
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/ajv/dist/index.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export * from './ajv';
|
||||
export * from './types';
|
||||
13
node_modules/@hookform/resolvers/ajv/dist/types.d.ts
generated
vendored
Normal file
13
node_modules/@hookform/resolvers/ajv/dist/types.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import * as Ajv from 'ajv';
|
||||
import type { DefinedError, ErrorObject } from 'ajv';
|
||||
import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
|
||||
export type Resolver = <T>(schema: Ajv.JSONSchemaType<T>, schemaOptions?: Ajv.Options, factoryOptions?: {
|
||||
mode?: 'async' | 'sync';
|
||||
}) => <TFieldValues extends FieldValues, TContext>(values: TFieldValues, context: TContext | undefined, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;
|
||||
type ErrorMessage = ErrorObject<'errorMessage', {
|
||||
errors: (DefinedError & {
|
||||
emUsed: boolean;
|
||||
})[];
|
||||
}>;
|
||||
export type AjvError = ErrorMessage | DefinedError;
|
||||
export {};
|
||||
20
node_modules/@hookform/resolvers/ajv/package.json
generated
vendored
Normal file
20
node_modules/@hookform/resolvers/ajv/package.json
generated
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
{
|
||||
"name": "@hookform/resolvers/ajv",
|
||||
"amdName": "hookformResolversAjv",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "React Hook Form validation resolver: ajv",
|
||||
"main": "dist/ajv.js",
|
||||
"module": "dist/ajv.module.js",
|
||||
"umd:main": "dist/ajv.umd.js",
|
||||
"source": "src/index.ts",
|
||||
"types": "dist/index.d.ts",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react-hook-form": "^7.55.0",
|
||||
"@hookform/resolvers": "^2.0.0",
|
||||
"ajv": "^8.12.0",
|
||||
"ajv-errors": "^3.0.0",
|
||||
"ajv-formats": "^2.1.1"
|
||||
}
|
||||
}
|
||||
94
node_modules/@hookform/resolvers/ajv/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
94
node_modules/@hookform/resolvers/ajv/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import { JSONSchemaType } from 'ajv';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { ajvResolver } from '..';
|
||||
|
||||
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
|
||||
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
|
||||
|
||||
type FormData = { username: string; password: string };
|
||||
|
||||
const schema: JSONSchemaType<FormData> = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
username: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
errorMessage: { minLength: USERNAME_REQUIRED_MESSAGE },
|
||||
},
|
||||
password: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
errorMessage: { minLength: PASSWORD_REQUIRED_MESSAGE },
|
||||
},
|
||||
},
|
||||
required: ['username', 'password'],
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
interface Props {
|
||||
onSubmit: (data: FormData) => void;
|
||||
}
|
||||
|
||||
function TestComponent({ onSubmit }: 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" />
|
||||
|
||||
<button type="submit">submit</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
test("form's native validation with Ajv", 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_REQUIRED_MESSAGE);
|
||||
|
||||
// password
|
||||
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
|
||||
expect(passwordField.validity.valid).toBe(false);
|
||||
expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE);
|
||||
|
||||
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('');
|
||||
});
|
||||
65
node_modules/@hookform/resolvers/ajv/src/__tests__/Form.tsx
generated
vendored
Normal file
65
node_modules/@hookform/resolvers/ajv/src/__tests__/Form.tsx
generated
vendored
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import { JSONSchemaType } from 'ajv';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { ajvResolver } from '..';
|
||||
|
||||
type FormData = { username: string; password: string };
|
||||
|
||||
const schema: JSONSchemaType<FormData> = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
username: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
errorMessage: { minLength: 'username field is required' },
|
||||
},
|
||||
password: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
errorMessage: { minLength: 'password field is required' },
|
||||
},
|
||||
},
|
||||
required: ['username', 'password'],
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
interface Props {
|
||||
onSubmit: (data: FormData) => void;
|
||||
}
|
||||
|
||||
function TestComponent({ onSubmit }: Props) {
|
||||
const {
|
||||
register,
|
||||
formState: { errors },
|
||||
handleSubmit,
|
||||
} = useForm<FormData>({
|
||||
resolver: ajvResolver(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 Ajv 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 field is required/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/password field is required/i)).toBeInTheDocument();
|
||||
expect(handleSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
216
node_modules/@hookform/resolvers/ajv/src/__tests__/__fixtures__/data-errors.ts
generated
vendored
Normal file
216
node_modules/@hookform/resolvers/ajv/src/__tests__/__fixtures__/data-errors.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
import { JSONSchemaType } from 'ajv';
|
||||
import { Field, InternalFieldName } from 'react-hook-form';
|
||||
|
||||
interface DataA {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export const schemaA: JSONSchemaType<DataA> = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
username: {
|
||||
type: 'string',
|
||||
minLength: 3,
|
||||
errorMessage: {
|
||||
minLength: 'username should be at least three characters long',
|
||||
},
|
||||
},
|
||||
password: {
|
||||
type: 'string',
|
||||
pattern: '.*[A-Z].*',
|
||||
minLength: 8,
|
||||
errorMessage: {
|
||||
pattern: 'One uppercase character',
|
||||
minLength: 'passwords should be at least eight characters long',
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['username', 'password'],
|
||||
additionalProperties: false,
|
||||
errorMessage: {
|
||||
required: {
|
||||
username: 'username field is required',
|
||||
password: 'password field is required',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const validDataA: DataA = {
|
||||
username: 'kt666',
|
||||
password: 'validPassword',
|
||||
};
|
||||
|
||||
export const invalidDataA = {
|
||||
username: 'kt',
|
||||
password: 'invalid',
|
||||
};
|
||||
|
||||
export const undefinedDataA = {
|
||||
username: undefined,
|
||||
password: undefined,
|
||||
};
|
||||
|
||||
export const fieldsA: 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',
|
||||
},
|
||||
};
|
||||
|
||||
// examples from [ajv-errors](https://github.com/ajv-validator/ajv-errors)
|
||||
|
||||
interface DataB {
|
||||
foo: number;
|
||||
}
|
||||
|
||||
export const schemaB: JSONSchemaType<DataB> = {
|
||||
type: 'object',
|
||||
required: ['foo'],
|
||||
properties: {
|
||||
foo: { type: 'integer' },
|
||||
},
|
||||
additionalProperties: false,
|
||||
errorMessage: 'should be an object with an integer property foo only',
|
||||
};
|
||||
|
||||
export const validDataB: DataB = { foo: 666 };
|
||||
export const invalidDataB = { foo: 'kt', bar: 6 };
|
||||
export const undefinedDataB = { foo: undefined };
|
||||
|
||||
interface DataC {
|
||||
foo: number;
|
||||
}
|
||||
|
||||
export const schemaC: JSONSchemaType<DataC> = {
|
||||
type: 'object',
|
||||
required: ['foo'],
|
||||
properties: {
|
||||
foo: { type: 'integer' },
|
||||
},
|
||||
additionalProperties: false,
|
||||
errorMessage: {
|
||||
type: 'should be an object',
|
||||
required: 'should have property foo',
|
||||
additionalProperties: 'should not have properties other than foo',
|
||||
},
|
||||
};
|
||||
|
||||
export const validDataC: DataC = { foo: 666 };
|
||||
export const invalidDataC = { foo: 'kt', bar: 6 };
|
||||
export const undefinedDataC = { foo: undefined };
|
||||
export const invalidTypeDataC = 'something';
|
||||
|
||||
interface DataD {
|
||||
foo: number;
|
||||
bar: string;
|
||||
}
|
||||
|
||||
export const schemaD: JSONSchemaType<DataD> = {
|
||||
type: 'object',
|
||||
required: ['foo', 'bar'],
|
||||
properties: {
|
||||
foo: { type: 'integer' },
|
||||
bar: { type: 'string' },
|
||||
},
|
||||
errorMessage: {
|
||||
type: 'should be an object', // will not replace internal "type" error for the property "foo"
|
||||
required: {
|
||||
foo: 'should have an integer property "foo"',
|
||||
bar: 'should have a string property "bar"',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const validDataD: DataD = { foo: 666, bar: 'kt' };
|
||||
export const invalidDataD = { foo: 'kt', bar: 6 };
|
||||
export const undefinedDataD = { foo: undefined, bar: undefined };
|
||||
export const invalidTypeDataD = 'something';
|
||||
|
||||
interface DataE {
|
||||
foo: number;
|
||||
bar: string;
|
||||
}
|
||||
|
||||
export const schemaE: JSONSchemaType<DataE> = {
|
||||
type: 'object',
|
||||
required: ['foo', 'bar'],
|
||||
allOf: [
|
||||
{
|
||||
properties: {
|
||||
foo: { type: 'integer', minimum: 2 },
|
||||
bar: { type: 'string', minLength: 2 },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
errorMessage: {
|
||||
properties: {
|
||||
foo: 'data.foo should be integer >= 2',
|
||||
bar: 'data.bar should be string with length >= 2',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const validDataE: DataE = { foo: 666, bar: 'kt' };
|
||||
export const invalidDataE = { foo: 1, bar: 'k' };
|
||||
export const undefinedDataE = { foo: undefined, bar: undefined };
|
||||
|
||||
interface DataF {
|
||||
foo: number;
|
||||
bar: string;
|
||||
}
|
||||
|
||||
export const schemaF: JSONSchemaType<DataF> = {
|
||||
type: 'object',
|
||||
required: ['foo', 'bar'],
|
||||
allOf: [
|
||||
{
|
||||
properties: {
|
||||
foo: { type: 'integer', minimum: 2 },
|
||||
bar: { type: 'string', minLength: 2 },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
errorMessage: {
|
||||
type: 'data should be an object',
|
||||
properties: {
|
||||
foo: 'data.foo should be integer >= 2',
|
||||
bar: 'data.bar should be string with length >= 2',
|
||||
},
|
||||
_: 'data should have properties "foo" and "bar" only',
|
||||
},
|
||||
};
|
||||
|
||||
export const validDataF: DataF = { foo: 666, bar: 'kt' };
|
||||
export const invalidDataF = {};
|
||||
export const undefinedDataF = { foo: 1, bar: undefined };
|
||||
export const invalidTypeDataF = 'something';
|
||||
|
||||
export const fieldsRest: Record<InternalFieldName, Field['_f']> = {
|
||||
foo: {
|
||||
ref: { name: 'foo' },
|
||||
name: 'foo',
|
||||
},
|
||||
bar: {
|
||||
ref: { name: 'bar' },
|
||||
name: 'bar',
|
||||
},
|
||||
lorem: {
|
||||
ref: { name: 'lorem' },
|
||||
name: 'lorem',
|
||||
},
|
||||
};
|
||||
90
node_modules/@hookform/resolvers/ajv/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
90
node_modules/@hookform/resolvers/ajv/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import { JSONSchemaType } from 'ajv';
|
||||
import { Field, InternalFieldName } from 'react-hook-form';
|
||||
|
||||
interface Data {
|
||||
username: string;
|
||||
password: string;
|
||||
deepObject: { data: string; twoLayersDeep: { name: string } };
|
||||
}
|
||||
|
||||
export const schema: 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'],
|
||||
},
|
||||
},
|
||||
required: ['data', 'twoLayersDeep'],
|
||||
},
|
||||
},
|
||||
required: ['username', 'password', 'deepObject'],
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
export const validData: Data = {
|
||||
username: 'jsun969',
|
||||
password: 'validPassword',
|
||||
deepObject: {
|
||||
twoLayersDeep: {
|
||||
name: 'deeper',
|
||||
},
|
||||
data: 'data',
|
||||
},
|
||||
};
|
||||
|
||||
export const invalidData = {
|
||||
username: '__',
|
||||
password: 'invalid-password',
|
||||
deepObject: {
|
||||
data: 233,
|
||||
twoLayersDeep: { name: 123 },
|
||||
},
|
||||
};
|
||||
|
||||
export const invalidDataWithUndefined = {
|
||||
username: 'jsun969',
|
||||
password: undefined,
|
||||
deepObject: {
|
||||
twoLayersDeep: {
|
||||
name: 'deeper',
|
||||
},
|
||||
data: undefined,
|
||||
},
|
||||
};
|
||||
|
||||
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',
|
||||
},
|
||||
};
|
||||
462
node_modules/@hookform/resolvers/ajv/src/__tests__/__snapshots__/ajv-errors.ts.snap
generated
vendored
Normal file
462
node_modules/@hookform/resolvers/ajv/src/__tests__/__snapshots__/ajv-errors.ts.snap
generated
vendored
Normal file
|
|
@ -0,0 +1,462 @@
|
|||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return a default message if there is no specific message for the error when requirement fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"bar": {
|
||||
"message": "data should have properties "foo" and "bar" only",
|
||||
"ref": {
|
||||
"name": "bar",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "data should have properties "foo" and "bar" only",
|
||||
},
|
||||
},
|
||||
"foo": {
|
||||
"message": "data should have properties "foo" and "bar" only",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "data should have properties "foo" and "bar" only",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return a default message if there is no specific message for the error when some properties are undefined 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"bar": {
|
||||
"message": "data should have properties "foo" and "bar" only",
|
||||
"ref": {
|
||||
"name": "bar",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "data should have properties "foo" and "bar" only",
|
||||
},
|
||||
},
|
||||
"foo": {
|
||||
"message": "data.foo should be integer >= 2",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "minimum",
|
||||
"types": {
|
||||
"minimum": "data.foo should be integer >= 2",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return a default message if there is no specific message for the error when walidation fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"bar": {
|
||||
"message": "data should have properties "foo" and "bar" only",
|
||||
"ref": {
|
||||
"name": "bar",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "data should have properties "foo" and "bar" only",
|
||||
},
|
||||
},
|
||||
"foo": {
|
||||
"message": "data should have properties "foo" and "bar" only",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "data should have properties "foo" and "bar" only",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return customized error messages for certain keywords when requirement fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"foo": {
|
||||
"message": "should have property foo",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "should have property foo",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return customized error messages for certain keywords when some properties are undefined 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"foo": {
|
||||
"message": "should have property foo",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "should have property foo",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return customized error messages for certain keywords when walidation fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"": {
|
||||
"message": "should not have properties other than foo",
|
||||
"ref": undefined,
|
||||
"type": "additionalProperties",
|
||||
"types": {
|
||||
"additionalProperties": "should not have properties other than foo",
|
||||
},
|
||||
},
|
||||
"foo": {
|
||||
"message": "must be integer",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "type",
|
||||
"types": {
|
||||
"type": "must be integer",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return customized error messages when requirement fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"password": {
|
||||
"message": "password field is required",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "password field is required",
|
||||
},
|
||||
},
|
||||
"username": {
|
||||
"message": "username field is required",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "username field is required",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return customized error messages when some properties are undefined 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"password": {
|
||||
"message": "password field is required",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "password field is required",
|
||||
},
|
||||
},
|
||||
"username": {
|
||||
"message": "username field is required",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "username field is required",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return customized error messages when validation fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"password": {
|
||||
"message": "One uppercase character",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "pattern",
|
||||
"types": {
|
||||
"minLength": "passwords should be at least eight characters long",
|
||||
"pattern": "One uppercase character",
|
||||
},
|
||||
},
|
||||
"username": {
|
||||
"message": "username should be at least three characters long",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "minLength",
|
||||
"types": {
|
||||
"minLength": "username should be at least three characters long",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return customized errors for properties/items when requirement fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"bar": {
|
||||
"message": "must have required property 'bar'",
|
||||
"ref": {
|
||||
"name": "bar",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "must have required property 'bar'",
|
||||
},
|
||||
},
|
||||
"foo": {
|
||||
"message": "must have required property 'foo'",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "must have required property 'foo'",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return customized errors for properties/items when some properties are undefined 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"bar": {
|
||||
"message": "must have required property 'bar'",
|
||||
"ref": {
|
||||
"name": "bar",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "must have required property 'bar'",
|
||||
},
|
||||
},
|
||||
"foo": {
|
||||
"message": "must have required property 'foo'",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "must have required property 'foo'",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return customized errors for properties/items when walidation fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"bar": {
|
||||
"message": "data.bar should be string with length >= 2",
|
||||
"ref": {
|
||||
"name": "bar",
|
||||
},
|
||||
"type": "minLength",
|
||||
"types": {
|
||||
"minLength": "data.bar should be string with length >= 2",
|
||||
},
|
||||
},
|
||||
"foo": {
|
||||
"message": "data.foo should be integer >= 2",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "minimum",
|
||||
"types": {
|
||||
"minimum": "data.foo should be integer >= 2",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return different messages for different properties when requirement fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"bar": {
|
||||
"message": "should have a string property "bar"",
|
||||
"ref": {
|
||||
"name": "bar",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "should have a string property "bar"",
|
||||
},
|
||||
},
|
||||
"foo": {
|
||||
"message": "should have an integer property "foo"",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "should have an integer property "foo"",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return different messages for different properties when some properties are undefined 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"bar": {
|
||||
"message": "should have a string property "bar"",
|
||||
"ref": {
|
||||
"name": "bar",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "should have a string property "bar"",
|
||||
},
|
||||
},
|
||||
"foo": {
|
||||
"message": "should have an integer property "foo"",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "should have an integer property "foo"",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return different messages for different properties when walidation fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"bar": {
|
||||
"message": "must be string",
|
||||
"ref": {
|
||||
"name": "bar",
|
||||
},
|
||||
"type": "type",
|
||||
"types": {
|
||||
"type": "must be string",
|
||||
},
|
||||
},
|
||||
"foo": {
|
||||
"message": "must be integer",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "type",
|
||||
"types": {
|
||||
"type": "must be integer",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return the same customized error message when requirement fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"foo": {
|
||||
"message": "should be an object with an integer property foo only",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "should be an object with an integer property foo only",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return the same customized message for all validation failures 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"": {
|
||||
"message": "should be an object with an integer property foo only",
|
||||
"ref": undefined,
|
||||
"type": "additionalProperties",
|
||||
"types": {
|
||||
"additionalProperties": "should be an object with an integer property foo only",
|
||||
},
|
||||
},
|
||||
"foo": {
|
||||
"message": "should be an object with an integer property foo only",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "type",
|
||||
"types": {
|
||||
"type": "should be an object with an integer property foo only",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver with errorMessage > should return the same customized message when some properties are undefined 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"foo": {
|
||||
"message": "should be an object with an integer property foo only",
|
||||
"ref": {
|
||||
"name": "foo",
|
||||
},
|
||||
"type": "required",
|
||||
"types": {
|
||||
"required": "should be an object with an integer property foo only",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
245
node_modules/@hookform/resolvers/ajv/src/__tests__/__snapshots__/ajv.ts.snap
generated
vendored
Normal file
245
node_modules/@hookform/resolvers/ajv/src/__tests__/__snapshots__/ajv.ts.snap
generated
vendored
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`ajvResolver > should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"deepObject": {
|
||||
"message": "must have required property 'deepObject'",
|
||||
"ref": undefined,
|
||||
"type": "required",
|
||||
},
|
||||
"password": {
|
||||
"message": "must have required property 'password'",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "required",
|
||||
},
|
||||
"username": {
|
||||
"message": "must have required property 'username'",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "required",
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver > should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true and \`mode: sync\` 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"deepObject": {
|
||||
"message": "must have required property 'deepObject'",
|
||||
"ref": undefined,
|
||||
"type": "required",
|
||||
},
|
||||
"password": {
|
||||
"message": "must have required property 'password'",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "required",
|
||||
},
|
||||
"username": {
|
||||
"message": "must have required property 'username'",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "required",
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver > should return all the error messages from ajvResolver when some property is undefined and result will keep the input data structure 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"deepObject": {
|
||||
"data": {
|
||||
"message": "must have required property 'data'",
|
||||
"ref": undefined,
|
||||
"type": "required",
|
||||
},
|
||||
},
|
||||
"password": {
|
||||
"message": "must have required property 'password'",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "required",
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver > should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"deepObject": {
|
||||
"data": {
|
||||
"message": "must be string",
|
||||
"ref": undefined,
|
||||
"type": "type",
|
||||
"types": {
|
||||
"type": "must be string",
|
||||
},
|
||||
},
|
||||
"twoLayersDeep": {
|
||||
"name": {
|
||||
"message": "must be string",
|
||||
"ref": undefined,
|
||||
"type": "type",
|
||||
"types": {
|
||||
"type": "must be string",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"password": {
|
||||
"message": "One uppercase character",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "pattern",
|
||||
"types": {
|
||||
"pattern": "One uppercase character",
|
||||
},
|
||||
},
|
||||
"username": {
|
||||
"message": "must NOT have fewer than 3 characters",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "minLength",
|
||||
"types": {
|
||||
"minLength": "must NOT have fewer than 3 characters",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver > should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true and \`mode: sync\` 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"deepObject": {
|
||||
"data": {
|
||||
"message": "must be string",
|
||||
"ref": undefined,
|
||||
"type": "type",
|
||||
"types": {
|
||||
"type": "must be string",
|
||||
},
|
||||
},
|
||||
"twoLayersDeep": {
|
||||
"name": {
|
||||
"message": "must be string",
|
||||
"ref": undefined,
|
||||
"type": "type",
|
||||
"types": {
|
||||
"type": "must be string",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"password": {
|
||||
"message": "One uppercase character",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "pattern",
|
||||
"types": {
|
||||
"pattern": "One uppercase character",
|
||||
},
|
||||
},
|
||||
"username": {
|
||||
"message": "must NOT have fewer than 3 characters",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "minLength",
|
||||
"types": {
|
||||
"minLength": "must NOT have fewer than 3 characters",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver > should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"deepObject": {
|
||||
"data": {
|
||||
"message": "must be string",
|
||||
"ref": undefined,
|
||||
"type": "type",
|
||||
},
|
||||
"twoLayersDeep": {
|
||||
"name": {
|
||||
"message": "must be string",
|
||||
"ref": undefined,
|
||||
"type": "type",
|
||||
},
|
||||
},
|
||||
},
|
||||
"password": {
|
||||
"message": "One uppercase character",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "pattern",
|
||||
},
|
||||
"username": {
|
||||
"message": "must NOT have fewer than 3 characters",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "minLength",
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ajvResolver > should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false and \`mode: sync\` 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"deepObject": {
|
||||
"data": {
|
||||
"message": "must be string",
|
||||
"ref": undefined,
|
||||
"type": "type",
|
||||
},
|
||||
"twoLayersDeep": {
|
||||
"name": {
|
||||
"message": "must be string",
|
||||
"ref": undefined,
|
||||
"type": "type",
|
||||
},
|
||||
},
|
||||
},
|
||||
"password": {
|
||||
"message": "One uppercase character",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "pattern",
|
||||
},
|
||||
"username": {
|
||||
"message": "must NOT have fewer than 3 characters",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "minLength",
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
227
node_modules/@hookform/resolvers/ajv/src/__tests__/ajv-errors.ts
generated
vendored
Normal file
227
node_modules/@hookform/resolvers/ajv/src/__tests__/ajv-errors.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
import { ajvResolver } from '..';
|
||||
import * as fixture from './__fixtures__/data-errors';
|
||||
|
||||
const shouldUseNativeValidation = false;
|
||||
|
||||
describe('ajvResolver with errorMessage', () => {
|
||||
it('should return values when validation pass', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaA)(fixture.validDataA, undefined, {
|
||||
fields: fixture.fieldsA,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toEqual({
|
||||
values: fixture.validDataA,
|
||||
errors: {},
|
||||
});
|
||||
});
|
||||
|
||||
it('should return customized error messages when validation fails', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaA)(
|
||||
fixture.invalidDataA,
|
||||
{},
|
||||
{
|
||||
fields: fixture.fieldsA,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return customized error messages when requirement fails', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaA)({}, undefined, {
|
||||
fields: fixture.fieldsA,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return customized error messages when some properties are undefined', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaA, undefined, { mode: 'sync' })(
|
||||
fixture.undefinedDataA,
|
||||
undefined,
|
||||
{
|
||||
fields: fixture.fieldsA,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return the same customized message for all validation failures', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaB)(
|
||||
fixture.invalidDataB,
|
||||
{},
|
||||
{
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return the same customized error message when requirement fails', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaB)({}, undefined, {
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return the same customized message when some properties are undefined', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaB)(fixture.undefinedDataB, undefined, {
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return customized error messages for certain keywords when walidation fails', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaC)(
|
||||
fixture.invalidDataC,
|
||||
{},
|
||||
{
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return customized error messages for certain keywords when requirement fails', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaC)({}, undefined, {
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return customized error messages for certain keywords when some properties are undefined', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaC)(fixture.undefinedDataC, undefined, {
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return different messages for different properties when walidation fails', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaD)(
|
||||
fixture.invalidDataD,
|
||||
{},
|
||||
{
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return different messages for different properties when requirement fails', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaD)({}, undefined, {
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return different messages for different properties when some properties are undefined', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaD)(fixture.undefinedDataD, undefined, {
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return customized errors for properties/items when walidation fails', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaE)(
|
||||
fixture.invalidDataE,
|
||||
{},
|
||||
{
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return customized errors for properties/items when requirement fails', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaE)({}, undefined, {
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return customized errors for properties/items when some properties are undefined', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaE)(fixture.undefinedDataE, undefined, {
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return a default message if there is no specific message for the error when walidation fails', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaF)(
|
||||
fixture.invalidDataF,
|
||||
{},
|
||||
{
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return a default message if there is no specific message for the error when requirement fails', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaF)({}, undefined, {
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return a default message if there is no specific message for the error when some properties are undefined', async () => {
|
||||
expect(
|
||||
await ajvResolver(fixture.schemaF)(fixture.undefinedDataF, undefined, {
|
||||
fields: fixture.fieldsRest,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
103
node_modules/@hookform/resolvers/ajv/src/__tests__/ajv.ts
generated
vendored
Normal file
103
node_modules/@hookform/resolvers/ajv/src/__tests__/ajv.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
import { ajvResolver } from '..';
|
||||
import {
|
||||
fields,
|
||||
invalidData,
|
||||
invalidDataWithUndefined,
|
||||
schema,
|
||||
validData,
|
||||
} from './__fixtures__/data';
|
||||
|
||||
const shouldUseNativeValidation = false;
|
||||
|
||||
describe('ajvResolver', () => {
|
||||
it('should return values from ajvResolver when validation pass', async () => {
|
||||
expect(
|
||||
await ajvResolver(schema)(validData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toEqual({
|
||||
values: validData,
|
||||
errors: {},
|
||||
});
|
||||
});
|
||||
|
||||
it('should return values from ajvResolver with `mode: sync` when validation pass', async () => {
|
||||
expect(
|
||||
await ajvResolver(schema, undefined, {
|
||||
mode: 'sync',
|
||||
})(validData, undefined, { fields, shouldUseNativeValidation }),
|
||||
).toEqual({
|
||||
values: validData,
|
||||
errors: {},
|
||||
});
|
||||
});
|
||||
|
||||
it('should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false', async () => {
|
||||
expect(
|
||||
await ajvResolver(schema)(invalidData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false and `mode: sync`', async () => {
|
||||
expect(
|
||||
await ajvResolver(schema, undefined, {
|
||||
mode: 'sync',
|
||||
})(invalidData, undefined, { fields, shouldUseNativeValidation }),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true', async () => {
|
||||
expect(
|
||||
await ajvResolver(schema)(
|
||||
invalidData,
|
||||
{},
|
||||
{ fields, criteriaMode: 'all', shouldUseNativeValidation },
|
||||
),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true and `mode: sync`', async () => {
|
||||
expect(
|
||||
await ajvResolver(schema, undefined, { mode: 'sync' })(
|
||||
invalidData,
|
||||
{},
|
||||
{ fields, criteriaMode: 'all', shouldUseNativeValidation },
|
||||
),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true', async () => {
|
||||
expect(
|
||||
await ajvResolver(schema)({}, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true and `mode: sync`', async () => {
|
||||
expect(
|
||||
await ajvResolver(schema, undefined, { mode: 'sync' })({}, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
}),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return all the error messages from ajvResolver when some property is undefined and result will keep the input data structure', async () => {
|
||||
expect(
|
||||
await ajvResolver(schema, undefined, { mode: 'sync' })(
|
||||
invalidDataWithUndefined,
|
||||
undefined,
|
||||
{
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
),
|
||||
).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
123
node_modules/@hookform/resolvers/ajv/src/ajv.ts
generated
vendored
Normal file
123
node_modules/@hookform/resolvers/ajv/src/ajv.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
|
||||
import Ajv, { DefinedError } from 'ajv';
|
||||
import ajvErrors from 'ajv-errors';
|
||||
import addFormats from 'ajv-formats';
|
||||
import { FieldError, appendErrors } from 'react-hook-form';
|
||||
import { AjvError, Resolver } from './types';
|
||||
|
||||
const parseErrorSchema = (
|
||||
ajvErrors: AjvError[],
|
||||
validateAllFieldCriteria: boolean,
|
||||
) => {
|
||||
const parsedErrors: Record<string, FieldError> = {};
|
||||
|
||||
const reduceError = (error: AjvError) => {
|
||||
// Ajv will return empty instancePath when require error
|
||||
if (error.keyword === 'required') {
|
||||
error.instancePath += `/${error.params.missingProperty}`;
|
||||
}
|
||||
|
||||
// `/deepObject/data` -> `deepObject.data`
|
||||
const path = error.instancePath.substring(1).replace(/\//g, '.');
|
||||
|
||||
if (!parsedErrors[path]) {
|
||||
parsedErrors[path] = {
|
||||
message: error.message,
|
||||
type: error.keyword,
|
||||
};
|
||||
}
|
||||
|
||||
if (validateAllFieldCriteria) {
|
||||
const types = parsedErrors[path].types;
|
||||
const messages = types && types[error.keyword];
|
||||
|
||||
parsedErrors[path] = appendErrors(
|
||||
path,
|
||||
validateAllFieldCriteria,
|
||||
parsedErrors,
|
||||
error.keyword,
|
||||
messages
|
||||
? ([] as string[]).concat(messages as string[], error.message || '')
|
||||
: error.message,
|
||||
) as FieldError;
|
||||
}
|
||||
};
|
||||
|
||||
for (let index = 0; index < ajvErrors.length; index += 1) {
|
||||
const error = ajvErrors[index];
|
||||
|
||||
if (error.keyword === 'errorMessage') {
|
||||
error.params.errors.forEach((originalError) => {
|
||||
originalError.message = error.message;
|
||||
reduceError(originalError);
|
||||
});
|
||||
} else {
|
||||
reduceError(error);
|
||||
}
|
||||
}
|
||||
|
||||
return parsedErrors;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a resolver for react-hook-form using Ajv schema validation
|
||||
* @param {Schema} schema - The Ajv schema to validate against
|
||||
* @param {Object} schemaOptions - Additional schema validation options
|
||||
* @param {Object} resolverOptions - Additional resolver configuration
|
||||
* @param {string} [resolverOptions.mode='async'] - Validation mode
|
||||
* @returns {Resolver<Schema>} A resolver function compatible with react-hook-form
|
||||
* @example
|
||||
* const schema = ajv.compile({
|
||||
* type: 'object',
|
||||
* properties: {
|
||||
* name: { type: 'string' },
|
||||
* age: { type: 'number' }
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* useForm({
|
||||
* resolver: ajvResolver(schema)
|
||||
* });
|
||||
*/
|
||||
export const ajvResolver: Resolver =
|
||||
(schema, schemaOptions, resolverOptions = {}) =>
|
||||
async (values, _, options) => {
|
||||
const ajv = new Ajv(
|
||||
Object.assign(
|
||||
{},
|
||||
{
|
||||
allErrors: true,
|
||||
validateSchema: true,
|
||||
},
|
||||
schemaOptions,
|
||||
),
|
||||
);
|
||||
|
||||
ajvErrors(ajv);
|
||||
addFormats(ajv);
|
||||
|
||||
const validate = ajv.compile(
|
||||
Object.assign(
|
||||
{ $async: resolverOptions && resolverOptions.mode === 'async' },
|
||||
schema,
|
||||
),
|
||||
);
|
||||
|
||||
const valid = validate(values);
|
||||
|
||||
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
|
||||
|
||||
return valid
|
||||
? { values, errors: {} }
|
||||
: {
|
||||
values: {},
|
||||
errors: toNestErrors(
|
||||
parseErrorSchema(
|
||||
validate.errors as DefinedError[],
|
||||
!options.shouldUseNativeValidation &&
|
||||
options.criteriaMode === 'all',
|
||||
),
|
||||
options,
|
||||
),
|
||||
};
|
||||
};
|
||||
2
node_modules/@hookform/resolvers/ajv/src/index.ts
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/ajv/src/index.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export * from './ajv';
|
||||
export * from './types';
|
||||
20
node_modules/@hookform/resolvers/ajv/src/types.ts
generated
vendored
Normal file
20
node_modules/@hookform/resolvers/ajv/src/types.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import * as Ajv from 'ajv';
|
||||
import type { DefinedError, ErrorObject } from 'ajv';
|
||||
import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
|
||||
|
||||
export type Resolver = <T>(
|
||||
schema: Ajv.JSONSchemaType<T>,
|
||||
schemaOptions?: Ajv.Options,
|
||||
factoryOptions?: { mode?: 'async' | 'sync' },
|
||||
) => <TFieldValues extends FieldValues, TContext>(
|
||||
values: TFieldValues,
|
||||
context: TContext | undefined,
|
||||
options: ResolverOptions<TFieldValues>,
|
||||
) => Promise<ResolverResult<TFieldValues>>;
|
||||
|
||||
// ajv doesn't export any types for errors with `keyword='errorMessage'`
|
||||
type ErrorMessage = ErrorObject<
|
||||
'errorMessage',
|
||||
{ errors: (DefinedError & { emUsed: boolean })[] }
|
||||
>;
|
||||
export type AjvError = ErrorMessage | DefinedError;
|
||||
8
node_modules/@hookform/resolvers/arktype/dist/arktype.d.ts
generated
vendored
Normal file
8
node_modules/@hookform/resolvers/arktype/dist/arktype.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import { StandardSchemaV1 } from '@standard-schema/spec';
|
||||
import { FieldValues, Resolver } from 'react-hook-form';
|
||||
export declare function arktypeResolver<Input extends FieldValues, Context, Output>(schema: StandardSchemaV1<Input, Output>, _schemaOptions?: never, resolverOptions?: {
|
||||
raw?: false;
|
||||
}): Resolver<Input, Context, Output>;
|
||||
export declare function arktypeResolver<Input extends FieldValues, Context, Output>(schema: StandardSchemaV1<Input, Output>, _schemaOptions: never | undefined, resolverOptions: {
|
||||
raw: true;
|
||||
}): Resolver<Input, Context, Input>;
|
||||
2
node_modules/@hookform/resolvers/arktype/dist/arktype.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/arktype/dist/arktype.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
var e=require("@hookform/resolvers");function r(){return r=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)({}).hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},r.apply(null,arguments)}function t(e){if(e.path?.length){let r="";for(const t of e.path){const e="object"==typeof t?t.key:t;if("string"!=typeof e&&"number"!=typeof e)return null;r+=r?`.${e}`:e}return r}return null}exports.arktypeResolver=function(n,s,o){return void 0===o&&(o={}),function(s,a,i){try{var u=function(){if(l.issues){var n=function(e,n){for(var s={},o=0;o<e.length;o++){var a=e[o],i=t(a);if(i&&(s[i]||(s[i]={message:a.message,type:""}),n)){var u,l=s[i].types||{};s[i].types=r({},l,((u={})[Object.keys(l).length]=a.message,u))}}return s}(l.issues,!i.shouldUseNativeValidation&&"all"===i.criteriaMode);return{values:{},errors:e.toNestErrors(n,i)}}return i.shouldUseNativeValidation&&e.validateFieldsNatively({},i),{values:o.raw?Object.assign({},s):l.value,errors:{}}},l=n["~standard"].validate(s),f=function(){if(l instanceof Promise)return Promise.resolve(l).then(function(e){l=e})}();return Promise.resolve(f&&f.then?f.then(u):u())}catch(e){return Promise.reject(e)}}};
|
||||
//# sourceMappingURL=arktype.js.map
|
||||
1
node_modules/@hookform/resolvers/arktype/dist/arktype.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/arktype/dist/arktype.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
2
node_modules/@hookform/resolvers/arktype/dist/arktype.mjs
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/arktype/dist/arktype.mjs
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{toNestErrors as e,validateFieldsNatively as r}from"@hookform/resolvers";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)({}).hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},t.apply(null,arguments)}function n(e){if(e.path?.length){let r="";for(const t of e.path){const e="object"==typeof t?t.key:t;if("string"!=typeof e&&"number"!=typeof e)return null;r+=r?`.${e}`:e}return r}return null}function o(o,s,i){return void 0===i&&(i={}),function(s,a,u){try{var l=function(){if(f.issues){var o=function(e,r){for(var o={},s=0;s<e.length;s++){var i=e[s],a=n(i);if(a&&(o[a]||(o[a]={message:i.message,type:""}),r)){var u,l=o[a].types||{};o[a].types=t({},l,((u={})[Object.keys(l).length]=i.message,u))}}return o}(f.issues,!u.shouldUseNativeValidation&&"all"===u.criteriaMode);return{values:{},errors:e(o,u)}}return u.shouldUseNativeValidation&&r({},u),{values:i.raw?Object.assign({},s):f.value,errors:{}}},f=o["~standard"].validate(s),c=function(){if(f instanceof Promise)return Promise.resolve(f).then(function(e){f=e})}();return Promise.resolve(c&&c.then?c.then(l):l())}catch(e){return Promise.reject(e)}}}export{o as arktypeResolver};
|
||||
//# sourceMappingURL=arktype.module.js.map
|
||||
2
node_modules/@hookform/resolvers/arktype/dist/arktype.modern.mjs
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/arktype/dist/arktype.modern.mjs
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{toNestErrors as e,validateFieldsNatively as t}from"@hookform/resolvers";function n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},n.apply(null,arguments)}function r(e){if(e.path?.length){let t="";for(const n of e.path){const e="object"==typeof n?n.key:n;if("string"!=typeof e&&"number"!=typeof e)return null;t+=t?`.${e}`:e}return t}return null}function s(s,o,a={}){return async(o,i,l)=>{let u=s["~standard"].validate(o);if(u instanceof Promise&&(u=await u),u.issues){const t=function(e,t){const s={};for(let o=0;o<e.length;o++){const a=e[o],i=r(a);if(i&&(s[i]||(s[i]={message:a.message,type:""}),t)){const e=s[i].types||{};s[i].types=n({},e,{[Object.keys(e).length]:a.message})}}return s}(u.issues,!l.shouldUseNativeValidation&&"all"===l.criteriaMode);return{values:{},errors:e(t,l)}}return l.shouldUseNativeValidation&&t({},l),{values:a.raw?Object.assign({},o):u.value,errors:{}}}}export{s as arktypeResolver};
|
||||
//# sourceMappingURL=arktype.modern.mjs.map
|
||||
1
node_modules/@hookform/resolvers/arktype/dist/arktype.modern.mjs.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/arktype/dist/arktype.modern.mjs.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
2
node_modules/@hookform/resolvers/arktype/dist/arktype.module.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/arktype/dist/arktype.module.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{toNestErrors as e,validateFieldsNatively as r}from"@hookform/resolvers";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)({}).hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},t.apply(null,arguments)}function n(e){if(e.path?.length){let r="";for(const t of e.path){const e="object"==typeof t?t.key:t;if("string"!=typeof e&&"number"!=typeof e)return null;r+=r?`.${e}`:e}return r}return null}function o(o,s,i){return void 0===i&&(i={}),function(s,a,u){try{var l=function(){if(f.issues){var o=function(e,r){for(var o={},s=0;s<e.length;s++){var i=e[s],a=n(i);if(a&&(o[a]||(o[a]={message:i.message,type:""}),r)){var u,l=o[a].types||{};o[a].types=t({},l,((u={})[Object.keys(l).length]=i.message,u))}}return o}(f.issues,!u.shouldUseNativeValidation&&"all"===u.criteriaMode);return{values:{},errors:e(o,u)}}return u.shouldUseNativeValidation&&r({},u),{values:i.raw?Object.assign({},s):f.value,errors:{}}},f=o["~standard"].validate(s),c=function(){if(f instanceof Promise)return Promise.resolve(f).then(function(e){f=e})}();return Promise.resolve(c&&c.then?c.then(l):l())}catch(e){return Promise.reject(e)}}}export{o as arktypeResolver};
|
||||
//# sourceMappingURL=arktype.module.js.map
|
||||
1
node_modules/@hookform/resolvers/arktype/dist/arktype.module.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/arktype/dist/arktype.module.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
2
node_modules/@hookform/resolvers/arktype/dist/arktype.umd.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/arktype/dist/arktype.umd.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers"],r):r((e||self).hookformResolversArktype={},e.hookformResolvers)}(this,function(e,r){function t(){return t=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var o in t)({}).hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},t.apply(null,arguments)}function o(e){if(e.path?.length){let r="";for(const t of e.path){const e="object"==typeof t?t.key:t;if("string"!=typeof e&&"number"!=typeof e)return null;r+=r?`.${e}`:e}return r}return null}e.arktypeResolver=function(e,n,s){return void 0===s&&(s={}),function(n,i,a){try{var f=function(){if(l.issues){var e=function(e,r){for(var n={},s=0;s<e.length;s++){var i=e[s],a=o(i);if(a&&(n[a]||(n[a]={message:i.message,type:""}),r)){var f,l=n[a].types||{};n[a].types=t({},l,((f={})[Object.keys(l).length]=i.message,f))}}return n}(l.issues,!a.shouldUseNativeValidation&&"all"===a.criteriaMode);return{values:{},errors:r.toNestErrors(e,a)}}return a.shouldUseNativeValidation&&r.validateFieldsNatively({},a),{values:s.raw?Object.assign({},n):l.value,errors:{}}},l=e["~standard"].validate(n),u=function(){if(l instanceof Promise)return Promise.resolve(l).then(function(e){l=e})}();return Promise.resolve(u&&u.then?u.then(f):f())}catch(e){return Promise.reject(e)}}}});
|
||||
//# sourceMappingURL=arktype.umd.js.map
|
||||
1
node_modules/@hookform/resolvers/arktype/dist/arktype.umd.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/arktype/dist/arktype.umd.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
1
node_modules/@hookform/resolvers/arktype/dist/index.d.ts
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/arktype/dist/index.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from './arktype';
|
||||
18
node_modules/@hookform/resolvers/arktype/package.json
generated
vendored
Normal file
18
node_modules/@hookform/resolvers/arktype/package.json
generated
vendored
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"name": "@hookform/resolvers/arktype",
|
||||
"amdName": "hookformResolversArktype",
|
||||
"version": "2.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.55.0",
|
||||
"@hookform/resolvers": "^2.0.0",
|
||||
"arktype": "^2.0.0"
|
||||
}
|
||||
}
|
||||
82
node_modules/@hookform/resolvers/arktype/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
82
node_modules/@hookform/resolvers/arktype/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import { type } from 'arktype';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { arktypeResolver } from '..';
|
||||
|
||||
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 Arktype", 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 at least length 2',
|
||||
);
|
||||
|
||||
// password
|
||||
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
|
||||
expect(passwordField.validity.valid).toBe(false);
|
||||
expect(passwordField.validationMessage).toBe(
|
||||
'password must be at least length 2',
|
||||
);
|
||||
|
||||
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('');
|
||||
});
|
||||
54
node_modules/@hookform/resolvers/arktype/src/__tests__/Form.tsx
generated
vendored
Normal file
54
node_modules/@hookform/resolvers/arktype/src/__tests__/Form.tsx
generated
vendored
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import { type } from 'arktype';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { arktypeResolver } from '..';
|
||||
|
||||
const schema = type({
|
||||
username: 'string>1',
|
||||
password: 'string>1',
|
||||
});
|
||||
|
||||
function TestComponent({
|
||||
onSubmit,
|
||||
}: {
|
||||
onSubmit: (data: typeof schema.infer) => void;
|
||||
}) {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm({
|
||||
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 at least length 2'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('password must be at least length 2'),
|
||||
).toBeInTheDocument();
|
||||
expect(handleSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
65
node_modules/@hookform/resolvers/arktype/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
65
node_modules/@hookform/resolvers/arktype/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
import { type } from 'arktype';
|
||||
import { Field, InternalFieldName } from 'react-hook-form';
|
||||
|
||||
export const schema = type({
|
||||
username: 'string>2',
|
||||
password: '/.*[A-Za-z].*/>8|/.*\\d.*/',
|
||||
repeatPassword: 'string>1',
|
||||
accessToken: 'string|number',
|
||||
birthYear: '1900<number<2013',
|
||||
email: 'string.email',
|
||||
tags: 'string[]',
|
||||
enabled: 'boolean',
|
||||
url: 'string>1',
|
||||
'like?': type({
|
||||
id: 'number',
|
||||
name: 'string>3',
|
||||
}).array(),
|
||||
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',
|
||||
} as any as typeof schema.infer;
|
||||
|
||||
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',
|
||||
},
|
||||
};
|
||||
74
node_modules/@hookform/resolvers/arktype/src/__tests__/__snapshots__/arktype.ts.snap
generated
vendored
Normal file
74
node_modules/@hookform/resolvers/arktype/src/__tests__/__snapshots__/arktype.ts.snap
generated
vendored
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
// 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 a number or a string (was missing)",
|
||||
"ref": undefined,
|
||||
"type": "required",
|
||||
},
|
||||
"birthYear": {
|
||||
"message": "birthYear must be a number (was a string)",
|
||||
"ref": undefined,
|
||||
"type": "domain",
|
||||
},
|
||||
"dateStr": {
|
||||
"message": "dateStr must be a Date (was missing)",
|
||||
"ref": undefined,
|
||||
"type": "required",
|
||||
},
|
||||
"email": {
|
||||
"message": "email must be an email address (was "")",
|
||||
"ref": {
|
||||
"name": "email",
|
||||
},
|
||||
"type": "pattern",
|
||||
},
|
||||
"enabled": {
|
||||
"message": "enabled must be boolean (was missing)",
|
||||
"ref": undefined,
|
||||
"type": "required",
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"id": {
|
||||
"message": "like[0].id must be a number (was a string)",
|
||||
"ref": undefined,
|
||||
"type": "domain",
|
||||
},
|
||||
"name": {
|
||||
"message": "like[0].name must be a string (was missing)",
|
||||
"ref": undefined,
|
||||
"type": "required",
|
||||
},
|
||||
},
|
||||
],
|
||||
"password": {
|
||||
"message": "password must be matched by .*[A-Za-z].* or matched by .*\\d.* (was "___")",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "union",
|
||||
},
|
||||
"repeatPassword": {
|
||||
"message": "repeatPassword must be a string (was missing)",
|
||||
"ref": undefined,
|
||||
"type": "required",
|
||||
},
|
||||
"tags": {
|
||||
"message": "tags must be an array (was missing)",
|
||||
"ref": undefined,
|
||||
"type": "required",
|
||||
},
|
||||
"username": {
|
||||
"message": "username must be a string (was missing)",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "required",
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
82
node_modules/@hookform/resolvers/arktype/src/__tests__/arktype.ts
generated
vendored
Normal file
82
node_modules/@hookform/resolvers/arktype/src/__tests__/arktype.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { type } from 'arktype';
|
||||
import { Resolver, useForm } from 'react-hook-form';
|
||||
import { SubmitHandler } from 'react-hook-form';
|
||||
import { arktypeResolver } from '..';
|
||||
import { fields, invalidData, schema, validData } 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();
|
||||
});
|
||||
|
||||
/**
|
||||
* Type inference tests
|
||||
*/
|
||||
it('should correctly infer the output type from a arktype schema', () => {
|
||||
const resolver = arktypeResolver(type({ id: 'number' }));
|
||||
|
||||
expectTypeOf(resolver).toEqualTypeOf<
|
||||
Resolver<{ id: number }, unknown, { id: number }>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a arktype schema using a transform', () => {
|
||||
const resolver = arktypeResolver(
|
||||
type({ id: type('string').pipe((s) => Number.parseInt(s)) }),
|
||||
);
|
||||
|
||||
expectTypeOf(resolver).toEqualTypeOf<
|
||||
Resolver<{ id: string }, unknown, { id: number }>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a arktype schema for the handleSubmit function in useForm', () => {
|
||||
const schema = type({ id: 'number' });
|
||||
|
||||
const form = useForm({
|
||||
resolver: arktypeResolver(schema),
|
||||
});
|
||||
|
||||
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
|
||||
|
||||
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
|
||||
SubmitHandler<{
|
||||
id: number;
|
||||
}>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a arktype schema with a transform for the handleSubmit function in useForm', () => {
|
||||
const schema = type({ id: type('string').pipe((s) => Number.parseInt(s)) });
|
||||
|
||||
const form = useForm({
|
||||
resolver: arktypeResolver(schema),
|
||||
});
|
||||
|
||||
expectTypeOf(form.watch('id')).toEqualTypeOf<string>();
|
||||
|
||||
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
|
||||
SubmitHandler<{
|
||||
id: number;
|
||||
}>
|
||||
>();
|
||||
});
|
||||
});
|
||||
98
node_modules/@hookform/resolvers/arktype/src/arktype.ts
generated
vendored
Normal file
98
node_modules/@hookform/resolvers/arktype/src/arktype.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
|
||||
import { StandardSchemaV1 } from '@standard-schema/spec';
|
||||
import { getDotPath } from '@standard-schema/utils';
|
||||
import { FieldError, FieldValues, Resolver } from 'react-hook-form';
|
||||
|
||||
function parseErrorSchema(
|
||||
issues: readonly StandardSchemaV1.Issue[],
|
||||
validateAllFieldCriteria: boolean,
|
||||
) {
|
||||
const errors: Record<string, FieldError> = {};
|
||||
|
||||
for (let i = 0; i < issues.length; i++) {
|
||||
const error = issues[i];
|
||||
const path = getDotPath(error);
|
||||
|
||||
if (path) {
|
||||
if (!errors[path]) {
|
||||
errors[path] = { message: error.message, type: '' };
|
||||
}
|
||||
|
||||
if (validateAllFieldCriteria) {
|
||||
const types = errors[path].types || {};
|
||||
|
||||
errors[path].types = {
|
||||
...types,
|
||||
[Object.keys(types).length]: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
export function arktypeResolver<Input extends FieldValues, Context, Output>(
|
||||
schema: StandardSchemaV1<Input, Output>,
|
||||
_schemaOptions?: never,
|
||||
resolverOptions?: {
|
||||
raw?: false;
|
||||
},
|
||||
): Resolver<Input, Context, Output>;
|
||||
|
||||
export function arktypeResolver<Input extends FieldValues, Context, Output>(
|
||||
schema: StandardSchemaV1<Input, Output>,
|
||||
_schemaOptions: never | undefined,
|
||||
resolverOptions: {
|
||||
raw: true;
|
||||
},
|
||||
): Resolver<Input, Context, Input>;
|
||||
|
||||
/**
|
||||
* Creates a resolver for react-hook-form using Arktype schema validation
|
||||
* @param {Schema} schema - The Arktype schema to validate against
|
||||
* @param {Object} resolverOptions - Additional resolver configuration
|
||||
* @param {string} [resolverOptions.mode='raw'] - Return the raw input values rather than the parsed values
|
||||
* @returns {Resolver<Schema['inferOut']>} A resolver function compatible with react-hook-form
|
||||
* @example
|
||||
* const schema = type({
|
||||
* username: 'string>2'
|
||||
* });
|
||||
*
|
||||
* useForm({
|
||||
* resolver: arktypeResolver(schema)
|
||||
* });
|
||||
*/
|
||||
export function arktypeResolver<Input extends FieldValues, Context, Output>(
|
||||
schema: StandardSchemaV1<Input, Output>,
|
||||
_schemaOptions?: never,
|
||||
resolverOptions: {
|
||||
raw?: boolean;
|
||||
} = {},
|
||||
): Resolver<Input, Context, Input | Output> {
|
||||
return async (values: Input, _, options) => {
|
||||
let result = schema['~standard'].validate(values);
|
||||
if (result instanceof Promise) {
|
||||
result = await result;
|
||||
}
|
||||
|
||||
if (result.issues) {
|
||||
const errors = parseErrorSchema(
|
||||
result.issues,
|
||||
!options.shouldUseNativeValidation && options.criteriaMode === 'all',
|
||||
);
|
||||
|
||||
return {
|
||||
values: {},
|
||||
errors: toNestErrors(errors, options),
|
||||
};
|
||||
}
|
||||
|
||||
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
|
||||
|
||||
return {
|
||||
values: resolverOptions.raw ? Object.assign({}, values) : result.value,
|
||||
errors: {},
|
||||
};
|
||||
};
|
||||
}
|
||||
1
node_modules/@hookform/resolvers/arktype/src/index.ts
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/arktype/src/index.ts
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from './arktype';
|
||||
29
node_modules/@hookform/resolvers/class-validator/dist/class-validator.d.ts
generated
vendored
Normal file
29
node_modules/@hookform/resolvers/class-validator/dist/class-validator.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { ClassConstructor, ClassTransformOptions } from 'class-transformer';
|
||||
import { ValidatorOptions } from 'class-validator';
|
||||
import { Resolver } from 'react-hook-form';
|
||||
/**
|
||||
* Creates a resolver for react-hook-form using class-validator schema validation
|
||||
* @param {ClassConstructor<Schema>} schema - The class-validator schema to validate against
|
||||
* @param {Object} schemaOptions - Additional schema validation options
|
||||
* @param {Object} resolverOptions - Additional resolver configuration
|
||||
* @param {string} [resolverOptions.mode='async'] - Validation mode
|
||||
* @returns {Resolver<Schema>} A resolver function compatible with react-hook-form
|
||||
* @example
|
||||
* class Schema {
|
||||
* @Matches(/^\w+$/)
|
||||
* @Length(3, 30)
|
||||
* username: string;
|
||||
* age: number
|
||||
* }
|
||||
*
|
||||
* useForm({
|
||||
* resolver: classValidatorResolver(Schema)
|
||||
* });
|
||||
*/
|
||||
export declare function classValidatorResolver<Schema extends Record<string, any>>(schema: ClassConstructor<Schema>, schemaOptions?: {
|
||||
validator?: ValidatorOptions;
|
||||
transformer?: ClassTransformOptions;
|
||||
}, resolverOptions?: {
|
||||
mode?: 'async' | 'sync';
|
||||
raw?: boolean;
|
||||
}): Resolver<Schema>;
|
||||
2
node_modules/@hookform/resolvers/class-validator/dist/class-validator.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/class-validator/dist/class-validator.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
var r=require("@hookform/resolvers"),e=require("class-transformer"),t=require("class-validator");function s(r,e,t,a){return void 0===t&&(t={}),void 0===a&&(a=""),r.reduce(function(r,t){var i=a?a+"."+t.property:t.property;if(t.constraints){var o=Object.keys(t.constraints)[0];r[i]={type:o,message:t.constraints[o]};var n=r[i];e&&n&&Object.assign(n,{types:t.constraints})}return t.children&&t.children.length&&s(t.children,e,r,i),r},t)}exports.classValidatorResolver=function(a,i,o){return void 0===i&&(i={}),void 0===o&&(o={}),function(n,l,c){try{var v=i.validator,d=e.plainToClass(a,n,i.transformer);return Promise.resolve(("sync"===o.mode?t.validateSync:t.validate)(d,v)).then(function(e){return e.length?{values:{},errors:r.toNestErrors(s(e,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)}:(c.shouldUseNativeValidation&&r.validateFieldsNatively({},c),{values:o.raw?Object.assign({},n):d,errors:{}})})}catch(r){return Promise.reject(r)}}};
|
||||
//# sourceMappingURL=class-validator.js.map
|
||||
1
node_modules/@hookform/resolvers/class-validator/dist/class-validator.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/class-validator/dist/class-validator.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"class-validator.js","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n ClassConstructor,\n ClassTransformOptions,\n plainToClass,\n} from 'class-transformer';\nimport {\n ValidationError,\n ValidatorOptions,\n validate,\n validateSync,\n} from 'class-validator';\nimport { FieldErrors, Resolver } from 'react-hook-form';\n\nfunction parseErrorSchema(\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using class-validator schema validation\n * @param {ClassConstructor<Schema>} schema - The class-validator schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver<Schema>} A resolver function compatible with react-hook-form\n * @example\n * class Schema {\n * @Matches(/^\\w+$/)\n * @Length(3, 30)\n * username: string;\n * age: number\n * }\n *\n * useForm({\n * resolver: classValidatorResolver(Schema)\n * });\n */\nexport function classValidatorResolver<Schema extends Record<string, any>>(\n schema: ClassConstructor<Schema>,\n schemaOptions: {\n validator?: ValidatorOptions;\n transformer?: ClassTransformOptions;\n } = {},\n resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},\n): Resolver<Schema> {\n return async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n errors: {},\n };\n };\n}\n"],"names":["parseErrorSchema","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","schema","schemaOptions","resolverOptions","values","_","options","validator","data","plainToClass","transformer","Promise","resolve","mode","validateSync","validate","then","rawErrors","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","raw","e","reject"],"mappings":"iGAcA,SAASA,EACPC,EACAC,EACAC,EACAC,GAEA,YAHA,IAAAD,IAAAA,EAA4B,CAAE,YAC9BC,IAAAA,EAAO,IAEAH,EAAOI,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAQJ,EAAUA,EAAI,IAAIG,EAAME,SAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,IAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,IAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAiBO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAG3DF,CACT,EAAGH,EACL,gCAqBM,SACJkB,EACAC,EAIAC,GAEA,gBANAD,IAAAA,EAGI,CAAE,QACN,IAAAC,IAAAA,EAA8D,CAAE,GAEhE,SAAcC,EAAQC,EAAGC,OACvB,IAAqBC,EAAcL,EAAdK,UACfC,EAAOC,EAAYA,aAACR,EAAQG,EADCF,EAA3BQ,aAC+C,OAAAC,QAAAC,SAEL,SAAzBT,EAAgBU,KACrCC,eACAC,EAAAA,UAAUP,EAAMD,IAAUS,KAFxBC,SAAAA,GAIN,OAAIA,EAAUjB,OACL,CACLI,OAAQ,CAAA,EACRvB,OAAQqC,eACNtC,EACEqC,GACCX,EAAQa,2BACkB,QAAzBb,EAAQc,cAEZd,KAKNA,EAAQa,2BAA6BE,EAAsBA,uBAAC,CAAE,EAAEf,GAEzD,CACLF,OAAQD,EAAgBmB,IAAM9B,OAAOK,OAAO,CAAE,EAAEO,GAAUI,EAC1D3B,OAAQ,CAAA,GACR,EACJ,CAAC,MAAA0C,GAAAZ,OAAAA,QAAAa,OAAAD,EACH,CAAA,CAAA"}
|
||||
2
node_modules/@hookform/resolvers/class-validator/dist/class-validator.mjs
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/class-validator/dist/class-validator.mjs
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{plainToClass as t}from"class-transformer";import{validateSync as o,validate as n}from"class-validator";function s(r,e,t,o){return void 0===t&&(t={}),void 0===o&&(o=""),r.reduce(function(r,t){var n=o?o+"."+t.property:t.property;if(t.constraints){var i=Object.keys(t.constraints)[0];r[n]={type:i,message:t.constraints[i]};var a=r[n];e&&a&&Object.assign(a,{types:t.constraints})}return t.children&&t.children.length&&s(t.children,e,r,n),r},t)}function i(i,a,c){return void 0===a&&(a={}),void 0===c&&(c={}),function(l,d,u){try{var v=a.validator,m=t(i,l,a.transformer);return Promise.resolve(("sync"===c.mode?o:n)(m,v)).then(function(t){return t.length?{values:{},errors:r(s(t,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)}:(u.shouldUseNativeValidation&&e({},u),{values:c.raw?Object.assign({},l):m,errors:{}})})}catch(r){return Promise.reject(r)}}}export{i as classValidatorResolver};
|
||||
//# sourceMappingURL=class-validator.module.js.map
|
||||
2
node_modules/@hookform/resolvers/class-validator/dist/class-validator.modern.mjs
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/class-validator/dist/class-validator.modern.mjs
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{toNestErrors as r,validateFieldsNatively as t}from"@hookform/resolvers";import{plainToClass as s}from"class-transformer";import{validateSync as e,validate as o}from"class-validator";function n(r,t,s={},e=""){return r.reduce((r,s)=>{const o=e?`${e}.${s.property}`:s.property;if(s.constraints){const e=Object.keys(s.constraints)[0];r[o]={type:e,message:s.constraints[e]};const n=r[o];t&&n&&Object.assign(n,{types:s.constraints})}return s.children&&s.children.length&&n(s.children,t,r,o),r},s)}function a(a,i={},c={}){return async(l,d,m)=>{const{transformer:u,validator:p}=i,f=s(a,l,u),h=await("sync"===c.mode?e:o)(f,p);return h.length?{values:{},errors:r(n(h,!m.shouldUseNativeValidation&&"all"===m.criteriaMode),m)}:(m.shouldUseNativeValidation&&t({},m),{values:c.raw?Object.assign({},l):f,errors:{}})}}export{a as classValidatorResolver};
|
||||
//# sourceMappingURL=class-validator.modern.mjs.map
|
||||
1
node_modules/@hookform/resolvers/class-validator/dist/class-validator.modern.mjs.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/class-validator/dist/class-validator.modern.mjs.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"class-validator.modern.mjs","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n ClassConstructor,\n ClassTransformOptions,\n plainToClass,\n} from 'class-transformer';\nimport {\n ValidationError,\n ValidatorOptions,\n validate,\n validateSync,\n} from 'class-validator';\nimport { FieldErrors, Resolver } from 'react-hook-form';\n\nfunction parseErrorSchema(\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using class-validator schema validation\n * @param {ClassConstructor<Schema>} schema - The class-validator schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver<Schema>} A resolver function compatible with react-hook-form\n * @example\n * class Schema {\n * @Matches(/^\\w+$/)\n * @Length(3, 30)\n * username: string;\n * age: number\n * }\n *\n * useForm({\n * resolver: classValidatorResolver(Schema)\n * });\n */\nexport function classValidatorResolver<Schema extends Record<string, any>>(\n schema: ClassConstructor<Schema>,\n schemaOptions: {\n validator?: ValidatorOptions;\n transformer?: ClassTransformOptions;\n } = {},\n resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},\n): Resolver<Schema> {\n return async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n errors: {},\n };\n };\n}\n"],"names":["parseErrorSchema","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","classValidatorResolver","schema","schemaOptions","resolverOptions","values","_","options","transformer","validator","data","plainToClass","rawErrors","mode","validateSync","validate","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","raw"],"mappings":"6LAcA,SAASA,EACPC,EACAC,EACAC,EAA4B,CAAA,EAC5BC,EAAO,IAEP,OAAOH,EAAOI,OAAO,CAACC,EAAKC,KACzB,MAAMC,EAAQJ,EAAO,GAAGA,KAAQG,EAAME,WAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,MAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,MAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAiBO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAG3DF,GACNH,EACL,CAqBgB,SAAAkB,EACdC,EACAC,EAGI,GACJC,EAA8D,CAAA,GAE9D,OAAcC,MAAAA,EAAQC,EAAGC,KACvB,MAAMC,YAAEA,EAAWC,UAAEA,GAAcN,EAC7BO,EAAOC,EAAaT,EAAQG,EAAQG,GAEpCI,QAA4C,SAAzBR,EAAgBS,KACrCC,EACAC,GAAUL,EAAMD,GAEpB,OAAIG,EAAUZ,OACL,CACLK,OAAQ,CAAA,EACRxB,OAAQmC,EACNpC,EACEgC,GACCL,EAAQU,2BACkB,QAAzBV,EAAQW,cAEZX,KAKNA,EAAQU,2BAA6BE,EAAuB,GAAIZ,GAEzD,CACLF,OAAQD,EAAgBgB,IAAM5B,OAAOK,OAAO,CAAA,EAAIQ,GAAUK,EAC1D7B,OAAQ,CAAA,IAGd"}
|
||||
2
node_modules/@hookform/resolvers/class-validator/dist/class-validator.module.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/class-validator/dist/class-validator.module.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{plainToClass as t}from"class-transformer";import{validateSync as o,validate as n}from"class-validator";function s(r,e,t,o){return void 0===t&&(t={}),void 0===o&&(o=""),r.reduce(function(r,t){var n=o?o+"."+t.property:t.property;if(t.constraints){var i=Object.keys(t.constraints)[0];r[n]={type:i,message:t.constraints[i]};var a=r[n];e&&a&&Object.assign(a,{types:t.constraints})}return t.children&&t.children.length&&s(t.children,e,r,n),r},t)}function i(i,a,c){return void 0===a&&(a={}),void 0===c&&(c={}),function(l,d,u){try{var v=a.validator,m=t(i,l,a.transformer);return Promise.resolve(("sync"===c.mode?o:n)(m,v)).then(function(t){return t.length?{values:{},errors:r(s(t,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)}:(u.shouldUseNativeValidation&&e({},u),{values:c.raw?Object.assign({},l):m,errors:{}})})}catch(r){return Promise.reject(r)}}}export{i as classValidatorResolver};
|
||||
//# sourceMappingURL=class-validator.module.js.map
|
||||
1
node_modules/@hookform/resolvers/class-validator/dist/class-validator.module.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/class-validator/dist/class-validator.module.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"class-validator.module.js","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n ClassConstructor,\n ClassTransformOptions,\n plainToClass,\n} from 'class-transformer';\nimport {\n ValidationError,\n ValidatorOptions,\n validate,\n validateSync,\n} from 'class-validator';\nimport { FieldErrors, Resolver } from 'react-hook-form';\n\nfunction parseErrorSchema(\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using class-validator schema validation\n * @param {ClassConstructor<Schema>} schema - The class-validator schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver<Schema>} A resolver function compatible with react-hook-form\n * @example\n * class Schema {\n * @Matches(/^\\w+$/)\n * @Length(3, 30)\n * username: string;\n * age: number\n * }\n *\n * useForm({\n * resolver: classValidatorResolver(Schema)\n * });\n */\nexport function classValidatorResolver<Schema extends Record<string, any>>(\n schema: ClassConstructor<Schema>,\n schemaOptions: {\n validator?: ValidatorOptions;\n transformer?: ClassTransformOptions;\n } = {},\n resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},\n): Resolver<Schema> {\n return async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n errors: {},\n };\n };\n}\n"],"names":["parseErrorSchema","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","classValidatorResolver","schema","schemaOptions","resolverOptions","values","_","options","validator","data","plainToClass","transformer","Promise","resolve","mode","validateSync","validate","then","rawErrors","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","raw","e","reject"],"mappings":"6LAcA,SAASA,EACPC,EACAC,EACAC,EACAC,GAEA,YAHA,IAAAD,IAAAA,EAA4B,CAAE,YAC9BC,IAAAA,EAAO,IAEAH,EAAOI,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAQJ,EAAUA,EAAI,IAAIG,EAAME,SAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,IAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,IAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAiBO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAG3DF,CACT,EAAGH,EACL,CAqBM,SAAUkB,EACdC,EACAC,EAIAC,GAEA,gBANAD,IAAAA,EAGI,CAAE,QACN,IAAAC,IAAAA,EAA8D,CAAE,GAEhE,SAAcC,EAAQC,EAAGC,OACvB,IAAqBC,EAAcL,EAAdK,UACfC,EAAOC,EAAaR,EAAQG,EADCF,EAA3BQ,aAC+C,OAAAC,QAAAC,SAEL,SAAzBT,EAAgBU,KACrCC,EACAC,GAAUP,EAAMD,IAAUS,KAFxBC,SAAAA,GAIN,OAAIA,EAAUlB,OACL,CACLK,OAAQ,CAAA,EACRxB,OAAQsC,EACNvC,EACEsC,GACCX,EAAQa,2BACkB,QAAzBb,EAAQc,cAEZd,KAKNA,EAAQa,2BAA6BE,EAAuB,CAAE,EAAEf,GAEzD,CACLF,OAAQD,EAAgBmB,IAAM/B,OAAOK,OAAO,CAAE,EAAEQ,GAAUI,EAC1D5B,OAAQ,CAAA,GACR,EACJ,CAAC,MAAA2C,GAAAZ,OAAAA,QAAAa,OAAAD,EACH,CAAA,CAAA"}
|
||||
2
node_modules/@hookform/resolvers/class-validator/dist/class-validator.umd.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/class-validator/dist/class-validator.umd.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("class-transformer"),require("class-validator")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","class-transformer","class-validator"],r):r((e||self).hookformResolversClassValidator={},e.hookformResolvers,e.classTransformer,e.classValidator)}(this,function(e,r,o,s){function t(e,r,o,s){return void 0===o&&(o={}),void 0===s&&(s=""),e.reduce(function(e,o){var a=s?s+"."+o.property:o.property;if(o.constraints){var i=Object.keys(o.constraints)[0];e[a]={type:i,message:o.constraints[i]};var n=e[a];r&&n&&Object.assign(n,{types:o.constraints})}return o.children&&o.children.length&&t(o.children,r,e,a),e},o)}e.classValidatorResolver=function(e,a,i){return void 0===a&&(a={}),void 0===i&&(i={}),function(n,l,c){try{var d=a.validator,f=o.plainToClass(e,n,a.transformer);return Promise.resolve(("sync"===i.mode?s.validateSync:s.validate)(f,d)).then(function(e){return e.length?{values:{},errors:r.toNestErrors(t(e,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)}:(c.shouldUseNativeValidation&&r.validateFieldsNatively({},c),{values:i.raw?Object.assign({},n):f,errors:{}})})}catch(e){return Promise.reject(e)}}}});
|
||||
//# sourceMappingURL=class-validator.umd.js.map
|
||||
1
node_modules/@hookform/resolvers/class-validator/dist/class-validator.umd.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/class-validator/dist/class-validator.umd.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"class-validator.umd.js","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n ClassConstructor,\n ClassTransformOptions,\n plainToClass,\n} from 'class-transformer';\nimport {\n ValidationError,\n ValidatorOptions,\n validate,\n validateSync,\n} from 'class-validator';\nimport { FieldErrors, Resolver } from 'react-hook-form';\n\nfunction parseErrorSchema(\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using class-validator schema validation\n * @param {ClassConstructor<Schema>} schema - The class-validator schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver<Schema>} A resolver function compatible with react-hook-form\n * @example\n * class Schema {\n * @Matches(/^\\w+$/)\n * @Length(3, 30)\n * username: string;\n * age: number\n * }\n *\n * useForm({\n * resolver: classValidatorResolver(Schema)\n * });\n */\nexport function classValidatorResolver<Schema extends Record<string, any>>(\n schema: ClassConstructor<Schema>,\n schemaOptions: {\n validator?: ValidatorOptions;\n transformer?: ClassTransformOptions;\n } = {},\n resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},\n): Resolver<Schema> {\n return async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n errors: {},\n };\n };\n}\n"],"names":["parseErrorSchema","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","schema","schemaOptions","resolverOptions","values","_","options","validator","data","plainToClass","transformer","Promise","resolve","mode","validateSync","validate","then","rawErrors","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","raw","e","reject"],"mappings":"0cAcA,SAASA,EACPC,EACAC,EACAC,EACAC,GAEA,YAHA,IAAAD,IAAAA,EAA4B,CAAE,YAC9BC,IAAAA,EAAO,IAEAH,EAAOI,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAQJ,EAAUA,EAAI,IAAIG,EAAME,SAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,IAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,IAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAiBO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAG3DF,CACT,EAAGH,EACL,0BAqBM,SACJkB,EACAC,EAIAC,GAEA,gBANAD,IAAAA,EAGI,CAAE,QACN,IAAAC,IAAAA,EAA8D,CAAE,GAEhE,SAAcC,EAAQC,EAAGC,OACvB,IAAqBC,EAAcL,EAAdK,UACfC,EAAOC,EAAYA,aAACR,EAAQG,EADCF,EAA3BQ,aAC+C,OAAAC,QAAAC,SAEL,SAAzBT,EAAgBU,KACrCC,eACAC,EAAAA,UAAUP,EAAMD,IAAUS,KAFxBC,SAAAA,GAIN,OAAIA,EAAUjB,OACL,CACLI,OAAQ,CAAA,EACRvB,OAAQqC,eACNtC,EACEqC,GACCX,EAAQa,2BACkB,QAAzBb,EAAQc,cAEZd,KAKNA,EAAQa,2BAA6BE,EAAsBA,uBAAC,CAAE,EAAEf,GAEzD,CACLF,OAAQD,EAAgBmB,IAAM9B,OAAOK,OAAO,CAAE,EAAEO,GAAUI,EAC1D3B,OAAQ,CAAA,GACR,EACJ,CAAC,MAAA0C,GAAAZ,OAAAA,QAAAa,OAAAD,EACH,CAAA,CAAA"}
|
||||
1
node_modules/@hookform/resolvers/class-validator/dist/index.d.ts
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/class-validator/dist/index.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from './class-validator';
|
||||
19
node_modules/@hookform/resolvers/class-validator/package.json
generated
vendored
Normal file
19
node_modules/@hookform/resolvers/class-validator/package.json
generated
vendored
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"name": "@hookform/resolvers/class-validator",
|
||||
"amdName": "hookformResolversClassValidator",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "React Hook Form validation resolver: class-validator",
|
||||
"main": "dist/class-validator.js",
|
||||
"module": "dist/class-validator.module.js",
|
||||
"umd:main": "dist/class-validator.umd.js",
|
||||
"source": "src/index.ts",
|
||||
"types": "dist/index.d.ts",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react-hook-form": ">=6.6.0",
|
||||
"@hookform/resolvers": ">=2.0.0",
|
||||
"class-transformer": "^0.4.0",
|
||||
"class-validator": "^0.12.0"
|
||||
}
|
||||
}
|
||||
79
node_modules/@hookform/resolvers/class-validator/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
79
node_modules/@hookform/resolvers/class-validator/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import { IsNotEmpty } from 'class-validator';
|
||||
import React from 'react';
|
||||
import { SubmitHandler, useForm } from 'react-hook-form';
|
||||
import { classValidatorResolver } from '..';
|
||||
|
||||
class Schema {
|
||||
@IsNotEmpty()
|
||||
username: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
password: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
onSubmit: SubmitHandler<Schema>;
|
||||
}
|
||||
|
||||
function TestComponent({ onSubmit }: Props) {
|
||||
const { register, handleSubmit } = useForm<Schema>({
|
||||
resolver: classValidatorResolver(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 Class Validator", 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 should not be empty');
|
||||
|
||||
// password
|
||||
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
|
||||
expect(passwordField.validity.valid).toBe(false);
|
||||
expect(passwordField.validationMessage).toBe('password should not be empty');
|
||||
|
||||
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('');
|
||||
});
|
||||
53
node_modules/@hookform/resolvers/class-validator/src/__tests__/Form.tsx
generated
vendored
Normal file
53
node_modules/@hookform/resolvers/class-validator/src/__tests__/Form.tsx
generated
vendored
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import { IsNotEmpty } from 'class-validator';
|
||||
import React from 'react';
|
||||
import { SubmitHandler, useForm } from 'react-hook-form';
|
||||
import { classValidatorResolver } from '..';
|
||||
|
||||
class Schema {
|
||||
@IsNotEmpty()
|
||||
username: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
password: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
onSubmit: SubmitHandler<Schema>;
|
||||
}
|
||||
|
||||
function TestComponent({ onSubmit }: Props) {
|
||||
const {
|
||||
register,
|
||||
formState: { errors },
|
||||
handleSubmit,
|
||||
} = useForm<Schema>({
|
||||
resolver: classValidatorResolver(Schema),
|
||||
});
|
||||
|
||||
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 Class Validator 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 should not be empty/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/password should not be empty/i)).toBeInTheDocument();
|
||||
expect(handleSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
88
node_modules/@hookform/resolvers/class-validator/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
88
node_modules/@hookform/resolvers/class-validator/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
import 'reflect-metadata';
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
IsEmail,
|
||||
IsNotEmpty,
|
||||
Length,
|
||||
Matches,
|
||||
Max,
|
||||
Min,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { Field, InternalFieldName } from 'react-hook-form';
|
||||
|
||||
class Like {
|
||||
@IsNotEmpty()
|
||||
id: number;
|
||||
|
||||
@Length(4)
|
||||
name: string;
|
||||
}
|
||||
|
||||
export class Schema {
|
||||
@Matches(/^\w+$/)
|
||||
@Length(3, 30)
|
||||
username: string;
|
||||
|
||||
@Matches(/^[a-zA-Z0-9]{3,30}/)
|
||||
password: string;
|
||||
|
||||
@Min(1900)
|
||||
@Max(2013)
|
||||
birthYear: number;
|
||||
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
accessToken: string;
|
||||
|
||||
tags: string[];
|
||||
|
||||
enabled: boolean;
|
||||
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => Like)
|
||||
like: Like[];
|
||||
}
|
||||
|
||||
export const validData: Schema = {
|
||||
username: 'Doe',
|
||||
password: 'Password123',
|
||||
birthYear: 2000,
|
||||
email: 'john@doe.com',
|
||||
tags: ['tag1', 'tag2'],
|
||||
enabled: true,
|
||||
accessToken: 'accessToken',
|
||||
like: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'name',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const invalidData = {
|
||||
password: '___',
|
||||
email: '',
|
||||
birthYear: 'birthYear',
|
||||
like: [{ id: 'z' }],
|
||||
} as any as Schema;
|
||||
|
||||
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',
|
||||
},
|
||||
};
|
||||
242
node_modules/@hookform/resolvers/class-validator/src/__tests__/__snapshots__/class-validator.ts.snap
generated
vendored
Normal file
242
node_modules/@hookform/resolvers/class-validator/src/__tests__/__snapshots__/class-validator.ts.snap
generated
vendored
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`classValidatorResolver > should return a single error from classValidatorResolver when validation fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"birthYear": {
|
||||
"message": "birthYear must not be greater than 2013",
|
||||
"ref": undefined,
|
||||
"type": "max",
|
||||
},
|
||||
"email": {
|
||||
"message": "email must be an email",
|
||||
"ref": {
|
||||
"name": "email",
|
||||
},
|
||||
"type": "isEmail",
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"name": {
|
||||
"message": "name must be longer than or equal to 4 characters",
|
||||
"ref": undefined,
|
||||
"type": "isLength",
|
||||
},
|
||||
},
|
||||
],
|
||||
"password": {
|
||||
"message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "matches",
|
||||
},
|
||||
"username": {
|
||||
"message": "username must be longer than or equal to 3 characters",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "isLength",
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`classValidatorResolver > should return a single error from classValidatorResolver with \`mode: sync\` when validation fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"birthYear": {
|
||||
"message": "birthYear must not be greater than 2013",
|
||||
"ref": undefined,
|
||||
"type": "max",
|
||||
},
|
||||
"email": {
|
||||
"message": "email must be an email",
|
||||
"ref": {
|
||||
"name": "email",
|
||||
},
|
||||
"type": "isEmail",
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"name": {
|
||||
"message": "name must be longer than or equal to 4 characters",
|
||||
"ref": undefined,
|
||||
"type": "isLength",
|
||||
},
|
||||
},
|
||||
],
|
||||
"password": {
|
||||
"message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "matches",
|
||||
},
|
||||
"username": {
|
||||
"message": "username must be longer than or equal to 3 characters",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "isLength",
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`classValidatorResolver > should return all the errors from classValidatorResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"birthYear": {
|
||||
"message": "birthYear must not be greater than 2013",
|
||||
"ref": undefined,
|
||||
"type": "max",
|
||||
"types": {
|
||||
"max": "birthYear must not be greater than 2013",
|
||||
"min": "birthYear must not be less than 1900",
|
||||
},
|
||||
},
|
||||
"email": {
|
||||
"message": "email must be an email",
|
||||
"ref": {
|
||||
"name": "email",
|
||||
},
|
||||
"type": "isEmail",
|
||||
"types": {
|
||||
"isEmail": "email must be an email",
|
||||
},
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"name": {
|
||||
"message": "name must be longer than or equal to 4 characters",
|
||||
"ref": undefined,
|
||||
"type": "isLength",
|
||||
"types": {
|
||||
"isLength": "name must be longer than or equal to 4 characters",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
"password": {
|
||||
"message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "matches",
|
||||
"types": {
|
||||
"matches": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
|
||||
},
|
||||
},
|
||||
"username": {
|
||||
"message": "username must be longer than or equal to 3 characters",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "isLength",
|
||||
"types": {
|
||||
"isLength": "username must be longer than or equal to 3 characters",
|
||||
"matches": "username must match /^\\w+$/ regular expression",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`classValidatorResolver > should return all the errors from classValidatorResolver when validation fails with \`validateAllFieldCriteria\` set to true and \`mode: sync\` 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"birthYear": {
|
||||
"message": "birthYear must not be greater than 2013",
|
||||
"ref": undefined,
|
||||
"type": "max",
|
||||
"types": {
|
||||
"max": "birthYear must not be greater than 2013",
|
||||
"min": "birthYear must not be less than 1900",
|
||||
},
|
||||
},
|
||||
"email": {
|
||||
"message": "email must be an email",
|
||||
"ref": {
|
||||
"name": "email",
|
||||
},
|
||||
"type": "isEmail",
|
||||
"types": {
|
||||
"isEmail": "email must be an email",
|
||||
},
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"name": {
|
||||
"message": "name must be longer than or equal to 4 characters",
|
||||
"ref": undefined,
|
||||
"type": "isLength",
|
||||
"types": {
|
||||
"isLength": "name must be longer than or equal to 4 characters",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
"password": {
|
||||
"message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "matches",
|
||||
"types": {
|
||||
"matches": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
|
||||
},
|
||||
},
|
||||
"username": {
|
||||
"message": "username must be longer than or equal to 3 characters",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "isLength",
|
||||
"types": {
|
||||
"isLength": "username must be longer than or equal to 3 characters",
|
||||
"matches": "username must match /^\\w+$/ regular expression",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`validate data with transformer option 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"random": {
|
||||
"message": "All fields must be defined.",
|
||||
"ref": undefined,
|
||||
"type": "isDefined",
|
||||
"types": {
|
||||
"isDefined": "All fields must be defined.",
|
||||
"isNumber": "Must be a number",
|
||||
"max": "Cannot be greater than 255",
|
||||
"min": "Cannot be lower than 0",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`validate data with validator option 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"random": {
|
||||
"message": "All fields must be defined.",
|
||||
"ref": undefined,
|
||||
"type": "isDefined",
|
||||
"types": {
|
||||
"isDefined": "All fields must be defined.",
|
||||
},
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
199
node_modules/@hookform/resolvers/class-validator/src/__tests__/class-validator.ts
generated
vendored
Normal file
199
node_modules/@hookform/resolvers/class-validator/src/__tests__/class-validator.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
import { Expose, Type } from 'class-transformer';
|
||||
import * as classValidator from 'class-validator';
|
||||
import { IsDefined, IsNumber, Max, Min } from 'class-validator';
|
||||
/* eslint-disable no-console, @typescript-eslint/ban-ts-comment */
|
||||
import { classValidatorResolver } from '..';
|
||||
import { Schema, fields, invalidData, validData } from './__fixtures__/data';
|
||||
|
||||
const shouldUseNativeValidation = false;
|
||||
|
||||
describe('classValidatorResolver', () => {
|
||||
it('should return values from classValidatorResolver when validation pass', async () => {
|
||||
const schemaSpy = vi.spyOn(classValidator, 'validate');
|
||||
const schemaSyncSpy = vi.spyOn(classValidator, 'validateSync');
|
||||
|
||||
const result = await classValidatorResolver(Schema)(validData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(schemaSpy).toHaveBeenCalledTimes(1);
|
||||
expect(schemaSyncSpy).not.toHaveBeenCalled();
|
||||
expect(result).toEqual({ errors: {}, values: validData });
|
||||
expect(result.values).toBeInstanceOf(Schema);
|
||||
});
|
||||
|
||||
it('should return values as a raw object from classValidatorResolver when `rawValues` set to true', async () => {
|
||||
const result = await classValidatorResolver(Schema, undefined, {
|
||||
raw: true,
|
||||
})(validData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(result).toEqual({ errors: {}, values: validData });
|
||||
expect(result.values).not.toBeInstanceOf(Schema);
|
||||
});
|
||||
|
||||
it('should return values from classValidatorResolver with `mode: sync` when validation pass', async () => {
|
||||
const validateSyncSpy = vi.spyOn(classValidator, 'validateSync');
|
||||
const validateSpy = vi.spyOn(classValidator, 'validate');
|
||||
|
||||
const result = await classValidatorResolver(Schema, undefined, {
|
||||
mode: 'sync',
|
||||
})(validData, undefined, { fields, shouldUseNativeValidation });
|
||||
|
||||
expect(validateSyncSpy).toHaveBeenCalledTimes(1);
|
||||
expect(validateSpy).not.toHaveBeenCalled();
|
||||
expect(result).toEqual({ errors: {}, values: validData });
|
||||
expect(result.values).toBeInstanceOf(Schema);
|
||||
});
|
||||
|
||||
it('should return a single error from classValidatorResolver when validation fails', async () => {
|
||||
const result = await classValidatorResolver(Schema)(
|
||||
invalidData,
|
||||
undefined,
|
||||
{
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return a single error from classValidatorResolver with `mode: sync` when validation fails', async () => {
|
||||
const validateSyncSpy = vi.spyOn(classValidator, 'validateSync');
|
||||
const validateSpy = vi.spyOn(classValidator, 'validate');
|
||||
|
||||
const result = await classValidatorResolver(Schema, undefined, {
|
||||
mode: 'sync',
|
||||
})(invalidData, undefined, { fields, shouldUseNativeValidation });
|
||||
|
||||
expect(validateSyncSpy).toHaveBeenCalledTimes(1);
|
||||
expect(validateSpy).not.toHaveBeenCalled();
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return all the errors from classValidatorResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
|
||||
const result = await classValidatorResolver(Schema)(
|
||||
invalidData,
|
||||
undefined,
|
||||
{
|
||||
fields,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return all the errors from classValidatorResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
|
||||
const result = await classValidatorResolver(Schema, undefined, {
|
||||
mode: 'sync',
|
||||
})(invalidData, undefined, {
|
||||
fields,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
it('validate data with transformer option', async () => {
|
||||
class SchemaTest {
|
||||
@Expose({ groups: ['find', 'create', 'update'] })
|
||||
@Type(() => Number)
|
||||
@IsDefined({
|
||||
message: `All fields must be defined.`,
|
||||
groups: ['publish'],
|
||||
})
|
||||
@IsNumber({}, { message: `Must be a number`, always: true })
|
||||
@Min(0, { message: `Cannot be lower than 0`, always: true })
|
||||
@Max(255, { message: `Cannot be greater than 255`, always: true })
|
||||
random: number;
|
||||
}
|
||||
|
||||
const result = await classValidatorResolver(
|
||||
SchemaTest,
|
||||
{ transformer: { groups: ['update'] } },
|
||||
{
|
||||
mode: 'sync',
|
||||
},
|
||||
)(
|
||||
// @ts-expect-error - Just for testing purposes
|
||||
invalidData,
|
||||
undefined,
|
||||
{
|
||||
fields,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('validate data with validator option', async () => {
|
||||
class SchemaTest {
|
||||
@Expose({ groups: ['find', 'create', 'update'] })
|
||||
@Type(() => Number)
|
||||
@IsDefined({
|
||||
message: `All fields must be defined.`,
|
||||
groups: ['publish'],
|
||||
})
|
||||
@IsNumber({}, { message: `Must be a number`, always: true })
|
||||
@Min(0, { message: `Cannot be lower than 0`, always: true })
|
||||
@Max(255, { message: `Cannot be greater than 255`, always: true })
|
||||
random: number;
|
||||
}
|
||||
|
||||
const result = await classValidatorResolver(
|
||||
SchemaTest,
|
||||
{ validator: { stopAtFirstError: true } },
|
||||
{
|
||||
mode: 'sync',
|
||||
},
|
||||
)(
|
||||
// @ts-expect-error - Just for testing purposes
|
||||
invalidData,
|
||||
undefined,
|
||||
{
|
||||
fields,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return from classValidatorResolver with `excludeExtraneousValues` set to true', async () => {
|
||||
class SchemaTest {
|
||||
@Expose()
|
||||
@IsNumber({}, { message: `Must be a number`, always: true })
|
||||
random: number;
|
||||
}
|
||||
|
||||
const result = await classValidatorResolver(SchemaTest, {
|
||||
transformer: {
|
||||
excludeExtraneousValues: true,
|
||||
},
|
||||
})(
|
||||
{
|
||||
random: 10,
|
||||
// @ts-expect-error - Just for testing purposes
|
||||
extraneousField: true,
|
||||
},
|
||||
undefined,
|
||||
{
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toEqual({ errors: {}, values: { random: 10 } });
|
||||
expect(result.values).toBeInstanceOf(SchemaTest);
|
||||
});
|
||||
101
node_modules/@hookform/resolvers/class-validator/src/class-validator.ts
generated
vendored
Normal file
101
node_modules/@hookform/resolvers/class-validator/src/class-validator.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
|
||||
import {
|
||||
ClassConstructor,
|
||||
ClassTransformOptions,
|
||||
plainToClass,
|
||||
} from 'class-transformer';
|
||||
import {
|
||||
ValidationError,
|
||||
ValidatorOptions,
|
||||
validate,
|
||||
validateSync,
|
||||
} from 'class-validator';
|
||||
import { FieldErrors, Resolver } from 'react-hook-form';
|
||||
|
||||
function parseErrorSchema(
|
||||
errors: ValidationError[],
|
||||
validateAllFieldCriteria: boolean,
|
||||
parsedErrors: FieldErrors = {},
|
||||
path = '',
|
||||
) {
|
||||
return errors.reduce((acc, error) => {
|
||||
const _path = path ? `${path}.${error.property}` : error.property;
|
||||
|
||||
if (error.constraints) {
|
||||
const key = Object.keys(error.constraints)[0];
|
||||
acc[_path] = {
|
||||
type: key,
|
||||
message: error.constraints[key],
|
||||
};
|
||||
|
||||
const _e = acc[_path];
|
||||
if (validateAllFieldCriteria && _e) {
|
||||
Object.assign(_e, { types: error.constraints });
|
||||
}
|
||||
}
|
||||
|
||||
if (error.children && error.children.length) {
|
||||
parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);
|
||||
}
|
||||
|
||||
return acc;
|
||||
}, parsedErrors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a resolver for react-hook-form using class-validator schema validation
|
||||
* @param {ClassConstructor<Schema>} schema - The class-validator schema to validate against
|
||||
* @param {Object} schemaOptions - Additional schema validation options
|
||||
* @param {Object} resolverOptions - Additional resolver configuration
|
||||
* @param {string} [resolverOptions.mode='async'] - Validation mode
|
||||
* @returns {Resolver<Schema>} A resolver function compatible with react-hook-form
|
||||
* @example
|
||||
* class Schema {
|
||||
* @Matches(/^\w+$/)
|
||||
* @Length(3, 30)
|
||||
* username: string;
|
||||
* age: number
|
||||
* }
|
||||
*
|
||||
* useForm({
|
||||
* resolver: classValidatorResolver(Schema)
|
||||
* });
|
||||
*/
|
||||
export function classValidatorResolver<Schema extends Record<string, any>>(
|
||||
schema: ClassConstructor<Schema>,
|
||||
schemaOptions: {
|
||||
validator?: ValidatorOptions;
|
||||
transformer?: ClassTransformOptions;
|
||||
} = {},
|
||||
resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},
|
||||
): Resolver<Schema> {
|
||||
return async (values, _, options) => {
|
||||
const { transformer, validator } = schemaOptions;
|
||||
const data = plainToClass(schema, values, transformer);
|
||||
|
||||
const rawErrors = await (resolverOptions.mode === 'sync'
|
||||
? validateSync
|
||||
: validate)(data, validator);
|
||||
|
||||
if (rawErrors.length) {
|
||||
return {
|
||||
values: {},
|
||||
errors: toNestErrors(
|
||||
parseErrorSchema(
|
||||
rawErrors,
|
||||
!options.shouldUseNativeValidation &&
|
||||
options.criteriaMode === 'all',
|
||||
),
|
||||
options,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
|
||||
|
||||
return {
|
||||
values: resolverOptions.raw ? Object.assign({}, values) : data,
|
||||
errors: {},
|
||||
};
|
||||
};
|
||||
}
|
||||
1
node_modules/@hookform/resolvers/class-validator/src/index.ts
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/class-validator/src/index.ts
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from './class-validator';
|
||||
17
node_modules/@hookform/resolvers/computed-types/dist/computed-types.d.ts
generated
vendored
Normal file
17
node_modules/@hookform/resolvers/computed-types/dist/computed-types.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import FunctionType from 'computed-types/lib/schema/FunctionType';
|
||||
import type { FieldValues, Resolver } from 'react-hook-form';
|
||||
/**
|
||||
* Creates a resolver for react-hook-form using computed-types schema validation
|
||||
* @param {Schema} schema - The computed-types schema to validate against
|
||||
* @returns {Resolver<Type<typeof schema>>} A resolver function compatible with react-hook-form
|
||||
* @example
|
||||
* const schema = Schema({
|
||||
* name: string,
|
||||
* age: number
|
||||
* });
|
||||
*
|
||||
* useForm({
|
||||
* resolver: computedTypesResolver(schema)
|
||||
* });
|
||||
*/
|
||||
export declare function computedTypesResolver<Input extends FieldValues, Context, Output>(schema: FunctionType<Output, [Input]>): Resolver<Input, Context, Output>;
|
||||
2
node_modules/@hookform/resolvers/computed-types/dist/computed-types.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/computed-types/dist/computed-types.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
var r=require("@hookform/resolvers");exports.computedTypesResolver=function(e){return function(t,o,n){try{return Promise.resolve(function(o,s){try{var u=Promise.resolve(e(t)).then(function(e){return n.shouldUseNativeValidation&&r.validateFieldsNatively({},n),{errors:{},values:e}})}catch(r){return s(r)}return u&&u.then?u.then(void 0,s):u}(0,function(e){if(function(r){return null!=r.errors}(e))return{values:{},errors:r.toNestErrors((t=e,(t.errors||[]).reduce(function(r,e){return r[e.path.join(".")]={type:e.error.name,message:e.error.message},r},{})),n)};var t;throw e}))}catch(r){return Promise.reject(r)}}};
|
||||
//# sourceMappingURL=computed-types.js.map
|
||||
1
node_modules/@hookform/resolvers/computed-types/dist/computed-types.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/computed-types/dist/computed-types.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"computed-types.js","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ValidationError } from 'computed-types';\nimport FunctionType from 'computed-types/lib/schema/FunctionType';\nimport type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nfunction parseErrorSchema(computedTypesError: ValidationError) {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using computed-types schema validation\n * @param {Schema} schema - The computed-types schema to validate against\n * @returns {Resolver<Type<typeof schema>>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema({\n * name: string,\n * age: number\n * });\n *\n * useForm({\n * resolver: computedTypesResolver(schema)\n * });\n */\nexport function computedTypesResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(schema: FunctionType<Output, [Input]>): Resolver<Input, Context, Output> {\n return async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n}\n"],"names":["schema","values","_","options","Promise","resolve","then","data","shouldUseNativeValidation","validateFieldsNatively","errors","_catch","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message","e","reject"],"mappings":"mEAkCM,SAIJA,GACA,OAAcC,SAAAA,EAAQC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,gCAC9BD,QAAAC,QACiBL,EAAOC,IAAOK,KAAA,SAA3BC,GAIN,OAFAJ,EAAQK,2BAA6BC,EAAAA,uBAAuB,CAAA,EAAIN,GAEzD,CACLO,OAAQ,CAAA,EACRT,OAAQM,EACR,4DAT8BI,CAAA,EAUjC,SAAQC,GACP,GA7CoB,SAACA,GACzB,OAAgB,MAAhBA,EAAMF,MAAc,CA4CZG,CAAkBD,GACpB,MAAO,CACLX,OAAQ,CAAE,EACVS,OAAQI,gBA7CQC,EA6CsBH,GA3CtCG,EAAmBL,QAAU,IAAIM,OAAO,SAACC,EAAKL,GAMpD,OALAK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,CACT,EARkC,CAAE,IA4CkBd,IA7CxD,IAA0BY,EAiDpB,MAAMH,CACR,GACF,CAAC,MAAAW,GAAAnB,OAAAA,QAAAoB,OAAAD,EACH,CAAA,CAAA"}
|
||||
2
node_modules/@hookform/resolvers/computed-types/dist/computed-types.mjs
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/computed-types/dist/computed-types.mjs
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function t(t){return function(n,o,u){try{return Promise.resolve(function(e,o){try{var s=Promise.resolve(t(n)).then(function(e){return u.shouldUseNativeValidation&&r({},u),{errors:{},values:e}})}catch(r){return o(r)}return s&&s.then?s.then(void 0,o):s}(0,function(r){if(function(r){return null!=r.errors}(r))return{values:{},errors:e((t=r,(t.errors||[]).reduce(function(r,e){return r[e.path.join(".")]={type:e.error.name,message:e.error.message},r},{})),u)};var t;throw r}))}catch(r){return Promise.reject(r)}}}export{t as computedTypesResolver};
|
||||
//# sourceMappingURL=computed-types.module.js.map
|
||||
2
node_modules/@hookform/resolvers/computed-types/dist/computed-types.modern.mjs
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/computed-types/dist/computed-types.modern.mjs
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function o(o){return async(s,t,a)=>{try{const e=await o(s);return a.shouldUseNativeValidation&&r({},a),{errors:{},values:e}}catch(r){if((r=>null!=r.errors)(r))return{values:{},errors:e((n=r,(n.errors||[]).reduce((r,e)=>(r[e.path.join(".")]={type:e.error.name,message:e.error.message},r),{})),a)};throw r}var n}}export{o as computedTypesResolver};
|
||||
//# sourceMappingURL=computed-types.modern.mjs.map
|
||||
1
node_modules/@hookform/resolvers/computed-types/dist/computed-types.modern.mjs.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/computed-types/dist/computed-types.modern.mjs.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"computed-types.modern.mjs","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ValidationError } from 'computed-types';\nimport FunctionType from 'computed-types/lib/schema/FunctionType';\nimport type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nfunction parseErrorSchema(computedTypesError: ValidationError) {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using computed-types schema validation\n * @param {Schema} schema - The computed-types schema to validate against\n * @returns {Resolver<Type<typeof schema>>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema({\n * name: string,\n * age: number\n * });\n *\n * useForm({\n * resolver: computedTypesResolver(schema)\n * });\n */\nexport function computedTypesResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(schema: FunctionType<Output, [Input]>): Resolver<Input, Context, Output> {\n return async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n}\n"],"names":["computedTypesResolver","schema","values","_","options","data","shouldUseNativeValidation","validateFieldsNatively","errors","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message"],"mappings":"+EAkCgB,SAAAA,EAIdC,GACA,aAAcC,EAAQC,EAAGC,KACvB,IACE,MAAMC,QAAaJ,EAAOC,GAI1B,OAFAE,EAAQE,2BAA6BC,EAAuB,CAAA,EAAIH,GAEzD,CACLI,OAAQ,CAAE,EACVN,OAAQG,EAEZ,CAAE,MAAOI,GACP,GA7CqBA,IACT,MAAhBA,EAAMD,OA4CEE,CAAkBD,GACpB,MAAO,CACLP,OAAQ,CAAE,EACVM,OAAQG,GA7CQC,EA6CsBH,GA3CtCG,EAAmBJ,QAAU,IAAIK,OAAO,CAACC,EAAKL,KACpDK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,GAPyB,KA4CoBV,IAIlD,MAAMK,CACR,CAlDJ,IAA0BG,CAkDtB,CAEJ"}
|
||||
2
node_modules/@hookform/resolvers/computed-types/dist/computed-types.module.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/computed-types/dist/computed-types.module.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function t(t){return function(n,o,u){try{return Promise.resolve(function(e,o){try{var s=Promise.resolve(t(n)).then(function(e){return u.shouldUseNativeValidation&&r({},u),{errors:{},values:e}})}catch(r){return o(r)}return s&&s.then?s.then(void 0,o):s}(0,function(r){if(function(r){return null!=r.errors}(r))return{values:{},errors:e((t=r,(t.errors||[]).reduce(function(r,e){return r[e.path.join(".")]={type:e.error.name,message:e.error.message},r},{})),u)};var t;throw r}))}catch(r){return Promise.reject(r)}}}export{t as computedTypesResolver};
|
||||
//# sourceMappingURL=computed-types.module.js.map
|
||||
1
node_modules/@hookform/resolvers/computed-types/dist/computed-types.module.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/computed-types/dist/computed-types.module.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"computed-types.module.js","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ValidationError } from 'computed-types';\nimport FunctionType from 'computed-types/lib/schema/FunctionType';\nimport type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nfunction parseErrorSchema(computedTypesError: ValidationError) {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using computed-types schema validation\n * @param {Schema} schema - The computed-types schema to validate against\n * @returns {Resolver<Type<typeof schema>>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema({\n * name: string,\n * age: number\n * });\n *\n * useForm({\n * resolver: computedTypesResolver(schema)\n * });\n */\nexport function computedTypesResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(schema: FunctionType<Output, [Input]>): Resolver<Input, Context, Output> {\n return async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n}\n"],"names":["computedTypesResolver","schema","values","_","options","Promise","resolve","then","data","shouldUseNativeValidation","validateFieldsNatively","errors","_catch","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message","e","reject"],"mappings":"+EAkCM,SAAUA,EAIdC,GACA,OAAcC,SAAAA,EAAQC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,gCAC9BD,QAAAC,QACiBL,EAAOC,IAAOK,KAAA,SAA3BC,GAIN,OAFAJ,EAAQK,2BAA6BC,EAAuB,CAAA,EAAIN,GAEzD,CACLO,OAAQ,CAAA,EACRT,OAAQM,EACR,4DAT8BI,CAAA,EAUjC,SAAQC,GACP,GA7CoB,SAACA,GACzB,OAAgB,MAAhBA,EAAMF,MAAc,CA4CZG,CAAkBD,GACpB,MAAO,CACLX,OAAQ,CAAE,EACVS,OAAQI,GA7CQC,EA6CsBH,GA3CtCG,EAAmBL,QAAU,IAAIM,OAAO,SAACC,EAAKL,GAMpD,OALAK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,CACT,EARkC,CAAE,IA4CkBd,IA7CxD,IAA0BY,EAiDpB,MAAMH,CACR,GACF,CAAC,MAAAW,GAAAnB,OAAAA,QAAAoB,OAAAD,EACH,CAAA,CAAA"}
|
||||
2
node_modules/@hookform/resolvers/computed-types/dist/computed-types.umd.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/computed-types/dist/computed-types.umd.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers"],r):r((e||self).hookformResolversComputedTypes={},e.hookformResolvers)}(this,function(e,r){e.computedTypesResolver=function(e){return function(o,t,n){try{return Promise.resolve(function(t,s){try{var i=Promise.resolve(e(o)).then(function(e){return n.shouldUseNativeValidation&&r.validateFieldsNatively({},n),{errors:{},values:e}})}catch(e){return s(e)}return i&&i.then?i.then(void 0,s):i}(0,function(e){if(function(e){return null!=e.errors}(e))return{values:{},errors:r.toNestErrors((o=e,(o.errors||[]).reduce(function(e,r){return e[r.path.join(".")]={type:r.error.name,message:r.error.message},e},{})),n)};var o;throw e}))}catch(e){return Promise.reject(e)}}}});
|
||||
//# sourceMappingURL=computed-types.umd.js.map
|
||||
1
node_modules/@hookform/resolvers/computed-types/dist/computed-types.umd.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/computed-types/dist/computed-types.umd.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"computed-types.umd.js","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ValidationError } from 'computed-types';\nimport FunctionType from 'computed-types/lib/schema/FunctionType';\nimport type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nfunction parseErrorSchema(computedTypesError: ValidationError) {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using computed-types schema validation\n * @param {Schema} schema - The computed-types schema to validate against\n * @returns {Resolver<Type<typeof schema>>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema({\n * name: string,\n * age: number\n * });\n *\n * useForm({\n * resolver: computedTypesResolver(schema)\n * });\n */\nexport function computedTypesResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(schema: FunctionType<Output, [Input]>): Resolver<Input, Context, Output> {\n return async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n}\n"],"names":["schema","values","_","options","Promise","resolve","then","data","shouldUseNativeValidation","validateFieldsNatively","errors","_catch","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message","e","reject"],"mappings":"2VAkCM,SAIJA,GACA,OAAcC,SAAAA,EAAQC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,gCAC9BD,QAAAC,QACiBL,EAAOC,IAAOK,KAAA,SAA3BC,GAIN,OAFAJ,EAAQK,2BAA6BC,EAAAA,uBAAuB,CAAA,EAAIN,GAEzD,CACLO,OAAQ,CAAA,EACRT,OAAQM,EACR,4DAT8BI,CAAA,EAUjC,SAAQC,GACP,GA7CoB,SAACA,GACzB,OAAgB,MAAhBA,EAAMF,MAAc,CA4CZG,CAAkBD,GACpB,MAAO,CACLX,OAAQ,CAAE,EACVS,OAAQI,gBA7CQC,EA6CsBH,GA3CtCG,EAAmBL,QAAU,IAAIM,OAAO,SAACC,EAAKL,GAMpD,OALAK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,CACT,EARkC,CAAE,IA4CkBd,IA7CxD,IAA0BY,EAiDpB,MAAMH,CACR,GACF,CAAC,MAAAW,GAAAnB,OAAAA,QAAAoB,OAAAD,EACH,CAAA,CAAA"}
|
||||
1
node_modules/@hookform/resolvers/computed-types/dist/index.d.ts
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/computed-types/dist/index.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from './computed-types';
|
||||
17
node_modules/@hookform/resolvers/computed-types/package.json
generated
vendored
Normal file
17
node_modules/@hookform/resolvers/computed-types/package.json
generated
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"name": "@hookform/resolvers/computed-types",
|
||||
"amdName": "hookformResolversComputedTypes",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "React Hook Form validation resolver: computed-types",
|
||||
"main": "dist/computed-types.js",
|
||||
"module": "dist/computed-types.module.js",
|
||||
"umd:main": "dist/computed-types.umd.js",
|
||||
"source": "src/index.ts",
|
||||
"types": "dist/index.d.ts",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react-hook-form": "^7.55.0",
|
||||
"@hookform/resolvers": "^2.0.0"
|
||||
}
|
||||
}
|
||||
79
node_modules/@hookform/resolvers/computed-types/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
79
node_modules/@hookform/resolvers/computed-types/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import Schema, { Type, string } from 'computed-types';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { computedTypesResolver } from '..';
|
||||
|
||||
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
|
||||
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
|
||||
|
||||
const schema = Schema({
|
||||
username: string.min(2).error(USERNAME_REQUIRED_MESSAGE),
|
||||
password: string.min(2).error(PASSWORD_REQUIRED_MESSAGE),
|
||||
});
|
||||
|
||||
interface Props {
|
||||
onSubmit: (data: Type<typeof schema>) => void;
|
||||
}
|
||||
|
||||
function TestComponent({ onSubmit }: Props) {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: computedTypesResolver(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 computed-types", 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_REQUIRED_MESSAGE);
|
||||
|
||||
// password
|
||||
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
|
||||
expect(passwordField.validity.valid).toBe(false);
|
||||
expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE);
|
||||
|
||||
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('');
|
||||
});
|
||||
57
node_modules/@hookform/resolvers/computed-types/src/__tests__/Form.tsx
generated
vendored
Normal file
57
node_modules/@hookform/resolvers/computed-types/src/__tests__/Form.tsx
generated
vendored
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import Schema, { Type, string } from 'computed-types';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { computedTypesResolver } from '..';
|
||||
|
||||
const schema = Schema({
|
||||
username: string.min(2).error('username field is required'),
|
||||
password: string.min(2).error('password field is required'),
|
||||
address: Schema({
|
||||
zipCode: string.min(5).max(5).error('zipCode field is required'),
|
||||
}),
|
||||
});
|
||||
|
||||
function TestComponent({
|
||||
onSubmit,
|
||||
}: { onSubmit: (data: Type<typeof schema>) => void }) {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm({
|
||||
resolver: computedTypesResolver(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>}
|
||||
|
||||
<input {...register('address.zipCode')} />
|
||||
{errors.address?.zipCode && (
|
||||
<span role="alert">{errors.address.zipCode.message}</span>
|
||||
)}
|
||||
|
||||
<button type="submit">submit</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
test("form's validation with computed-types 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 field is required/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/password field is required/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/zipCode field is required/i)).toBeInTheDocument();
|
||||
expect(handleSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
86
node_modules/@hookform/resolvers/computed-types/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
86
node_modules/@hookform/resolvers/computed-types/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
import Schema, { Type, string, number, array, boolean } from 'computed-types';
|
||||
import { Field, InternalFieldName } from 'react-hook-form';
|
||||
|
||||
export const schema = Schema({
|
||||
username: string.regexp(/^\w+$/).min(3).max(30),
|
||||
password: string
|
||||
.regexp(new RegExp('.*[A-Z].*'), 'One uppercase character')
|
||||
.regexp(new RegExp('.*[a-z].*'), 'One lowercase character')
|
||||
.regexp(new RegExp('.*\\d.*'), 'One number')
|
||||
.regexp(
|
||||
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
|
||||
'One special character',
|
||||
)
|
||||
.min(8, 'Must be at least 8 characters in length'),
|
||||
repeatPassword: string,
|
||||
accessToken: Schema.either(string, number).optional(),
|
||||
birthYear: number.min(1900).max(2013).optional(),
|
||||
email: string
|
||||
.regexp(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/)
|
||||
.error('Incorrect email'),
|
||||
tags: array.of(string),
|
||||
enabled: boolean,
|
||||
like: array
|
||||
.of({
|
||||
id: number,
|
||||
name: string.min(4).max(4),
|
||||
})
|
||||
.optional(),
|
||||
address: Schema({
|
||||
city: string.min(3, 'Is required'),
|
||||
zipCode: string
|
||||
.min(5, 'Must be 5 characters long')
|
||||
.max(5, 'Must be 5 characters long'),
|
||||
}),
|
||||
});
|
||||
|
||||
export const validData: Type<typeof schema> = {
|
||||
username: 'Doe',
|
||||
password: 'Password123_',
|
||||
repeatPassword: 'Password123_',
|
||||
accessToken: 'accessToken',
|
||||
birthYear: 2000,
|
||||
email: 'john@doe.com',
|
||||
tags: ['tag1', 'tag2'],
|
||||
enabled: true,
|
||||
like: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'name',
|
||||
},
|
||||
],
|
||||
address: {
|
||||
city: 'Awesome city',
|
||||
zipCode: '12345',
|
||||
},
|
||||
};
|
||||
|
||||
export const invalidData = {
|
||||
password: '___',
|
||||
email: '',
|
||||
birthYear: 'birthYear',
|
||||
like: [{ id: 'z' }],
|
||||
address: {
|
||||
city: '',
|
||||
zipCode: '123',
|
||||
},
|
||||
} as any as Type<typeof schema>;
|
||||
|
||||
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',
|
||||
},
|
||||
};
|
||||
74
node_modules/@hookform/resolvers/computed-types/src/__tests__/__snapshots__/computed-types.ts.snap
generated
vendored
Normal file
74
node_modules/@hookform/resolvers/computed-types/src/__tests__/__snapshots__/computed-types.ts.snap
generated
vendored
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`computedTypesResolver > should return a single error from computedTypesResolver when validation fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"address": {
|
||||
"city": {
|
||||
"message": "Is required",
|
||||
"ref": undefined,
|
||||
"type": "ValidationError",
|
||||
},
|
||||
"zipCode": {
|
||||
"message": "Must be 5 characters long",
|
||||
"ref": undefined,
|
||||
"type": "ValidationError",
|
||||
},
|
||||
},
|
||||
"birthYear": {
|
||||
"message": "Expect value to be "number"",
|
||||
"ref": undefined,
|
||||
"type": "ValidationError",
|
||||
},
|
||||
"email": {
|
||||
"message": "Incorrect email",
|
||||
"ref": {
|
||||
"name": "email",
|
||||
},
|
||||
"type": "ValidationError",
|
||||
},
|
||||
"enabled": {
|
||||
"message": "Expect value to be "boolean"",
|
||||
"ref": undefined,
|
||||
"type": "ValidationError",
|
||||
},
|
||||
"like": {
|
||||
"id": {
|
||||
"message": "Expect value to be "number"",
|
||||
"ref": undefined,
|
||||
"type": "ValidationError",
|
||||
},
|
||||
"name": {
|
||||
"message": "Expect value to be "string"",
|
||||
"ref": undefined,
|
||||
"type": "ValidationError",
|
||||
},
|
||||
},
|
||||
"password": {
|
||||
"message": "One uppercase character",
|
||||
"ref": {
|
||||
"name": "password",
|
||||
},
|
||||
"type": "ValidationError",
|
||||
},
|
||||
"repeatPassword": {
|
||||
"message": "Expect value to be "string"",
|
||||
"ref": undefined,
|
||||
"type": "ValidationError",
|
||||
},
|
||||
"tags": {
|
||||
"message": "Expecting value to be an array",
|
||||
"ref": undefined,
|
||||
"type": "ValidationError",
|
||||
},
|
||||
"username": {
|
||||
"message": "Expect value to be "string"",
|
||||
"ref": {
|
||||
"name": "username",
|
||||
},
|
||||
"type": "ValidationError",
|
||||
},
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
96
node_modules/@hookform/resolvers/computed-types/src/__tests__/computed-types.ts
generated
vendored
Normal file
96
node_modules/@hookform/resolvers/computed-types/src/__tests__/computed-types.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
import Schema, { number } from 'computed-types';
|
||||
import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
|
||||
import { computedTypesResolver } from '..';
|
||||
import { fields, invalidData, schema, validData } from './__fixtures__/data';
|
||||
|
||||
const shouldUseNativeValidation = false;
|
||||
|
||||
describe('computedTypesResolver', () => {
|
||||
it('should return values from computedTypesResolver when validation pass', async () => {
|
||||
const result = await computedTypesResolver(schema)(validData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(result).toEqual({ errors: {}, values: validData });
|
||||
});
|
||||
|
||||
it('should return a single error from computedTypesResolver when validation fails', async () => {
|
||||
const result = await computedTypesResolver(schema)(invalidData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should throw any error unrelated to computed-types', async () => {
|
||||
const schemaWithCustomError = schema.transform(() => {
|
||||
throw Error('custom error');
|
||||
});
|
||||
|
||||
const promise = computedTypesResolver(schemaWithCustomError)(
|
||||
validData,
|
||||
undefined,
|
||||
{
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
},
|
||||
);
|
||||
|
||||
await expect(promise).rejects.toThrow('custom error');
|
||||
});
|
||||
|
||||
/**
|
||||
* Type inference tests
|
||||
*/
|
||||
it('should correctly infer the output type from a computedTypes schema', () => {
|
||||
const resolver = computedTypesResolver(Schema({ id: number }));
|
||||
|
||||
expectTypeOf(resolver).toEqualTypeOf<
|
||||
Resolver<{ id: number }, unknown, { id: number }>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a computedTypes schema using a transform', () => {
|
||||
const resolver = computedTypesResolver(
|
||||
Schema({ id: number.transform((val) => String(val)) }),
|
||||
);
|
||||
|
||||
expectTypeOf(resolver).toEqualTypeOf<
|
||||
Resolver<{ id: number }, unknown, { id: string }>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a computedTypes schema for the handleSubmit function in useForm', () => {
|
||||
const schema = Schema({ id: number });
|
||||
|
||||
const form = useForm({
|
||||
resolver: computedTypesResolver(schema),
|
||||
});
|
||||
|
||||
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
|
||||
|
||||
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
|
||||
SubmitHandler<{
|
||||
id: number;
|
||||
}>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a computedTypes schema with a transform for the handleSubmit function in useForm', () => {
|
||||
const schema = Schema({ id: number.transform((val) => String(val)) });
|
||||
|
||||
const form = useForm({
|
||||
resolver: computedTypesResolver(schema),
|
||||
});
|
||||
|
||||
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
|
||||
|
||||
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
|
||||
SubmitHandler<{
|
||||
id: string;
|
||||
}>
|
||||
>();
|
||||
});
|
||||
});
|
||||
61
node_modules/@hookform/resolvers/computed-types/src/computed-types.ts
generated
vendored
Normal file
61
node_modules/@hookform/resolvers/computed-types/src/computed-types.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
|
||||
import { ValidationError } from 'computed-types';
|
||||
import FunctionType from 'computed-types/lib/schema/FunctionType';
|
||||
import type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';
|
||||
|
||||
const isValidationError = (error: any): error is ValidationError =>
|
||||
error.errors != null;
|
||||
|
||||
function parseErrorSchema(computedTypesError: ValidationError) {
|
||||
const parsedErrors: FieldErrors = {};
|
||||
return (computedTypesError.errors || []).reduce((acc, error) => {
|
||||
acc[error.path.join('.')] = {
|
||||
type: error.error.name,
|
||||
message: error.error.message,
|
||||
};
|
||||
|
||||
return acc;
|
||||
}, parsedErrors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a resolver for react-hook-form using computed-types schema validation
|
||||
* @param {Schema} schema - The computed-types schema to validate against
|
||||
* @returns {Resolver<Type<typeof schema>>} A resolver function compatible with react-hook-form
|
||||
* @example
|
||||
* const schema = Schema({
|
||||
* name: string,
|
||||
* age: number
|
||||
* });
|
||||
*
|
||||
* useForm({
|
||||
* resolver: computedTypesResolver(schema)
|
||||
* });
|
||||
*/
|
||||
export function computedTypesResolver<
|
||||
Input extends FieldValues,
|
||||
Context,
|
||||
Output,
|
||||
>(schema: FunctionType<Output, [Input]>): Resolver<Input, Context, Output> {
|
||||
return async (values, _, options) => {
|
||||
try {
|
||||
const data = await schema(values);
|
||||
|
||||
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
|
||||
|
||||
return {
|
||||
errors: {},
|
||||
values: data,
|
||||
};
|
||||
} catch (error: any) {
|
||||
if (isValidationError(error)) {
|
||||
return {
|
||||
values: {},
|
||||
errors: toNestErrors(parseErrorSchema(error), options),
|
||||
};
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
1
node_modules/@hookform/resolvers/computed-types/src/index.ts
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/computed-types/src/index.ts
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from './computed-types';
|
||||
2
node_modules/@hookform/resolvers/dist/index.d.ts
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/dist/index.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export * from './toNestErrors';
|
||||
export * from './validateFieldsNatively';
|
||||
2
node_modules/@hookform/resolvers/dist/resolvers.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/dist/resolvers.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
var e=require("react-hook-form"),r=function(r,t,i){if(r&&"reportValidity"in r){var n=e.get(i,t);r.setCustomValidity(n&&n.message||""),r.reportValidity()}},t=function(e,t){var i=function(i){var n=t.fields[i];n&&n.ref&&"reportValidity"in n.ref?r(n.ref,i,e):n&&n.refs&&n.refs.forEach(function(t){return r(t,i,e)})};for(var n in t.fields)i(n)},i=function(e,r){var t=n(r);return e.some(function(e){return n(e).match("^"+t+"\\.\\d+")})};function n(e){return e.replace(/\]|\[/g,"")}exports.toNestErrors=function(r,n){n.shouldUseNativeValidation&&t(r,n);var a={};for(var o in r){var s=e.get(n.fields,o),f=Object.assign(r[o]||{},{ref:s&&s.ref});if(i(n.names||Object.keys(r),o)){var u=Object.assign({},e.get(a,o));e.set(u,"root",f),e.set(a,o,u)}else e.set(a,o,f)}return a},exports.validateFieldsNatively=t;
|
||||
//# sourceMappingURL=resolvers.js.map
|
||||
1
node_modules/@hookform/resolvers/dist/resolvers.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/dist/resolvers.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"resolvers.js","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field && field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): FieldErrors<TFieldValues> => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors<TFieldValues>;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => {\n const path = escapeBrackets(name);\n return names.some((n) => escapeBrackets(n).match(`^${path}\\\\.\\\\d+`));\n};\n\n/**\n * Escapes special characters in a string to be used in a regex pattern.\n * it removes the brackets from the string to match the `set` method.\n *\n * @param input - The input string to escape.\n * @returns The escaped string.\n */\nfunction escapeBrackets(input: string): string {\n return input.replace(/\\]|\\[/g, '');\n}\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","_loop","field","fields","refs","forEach","isNameInFieldArray","names","name","path","escapeBrackets","some","n","match","input","replace","shouldUseNativeValidation","fieldErrors","Object","assign","keys","fieldArrayErrors","set"],"mappings":"iCASMA,EAAoB,SACxBC,EACAC,EACAC,GAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,IAAMG,EAAQC,MAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,CACF,EAGaC,EAAyB,SACpCL,EACAM,GACQC,IAAAA,WAAAR,GAEN,IAAMS,EAAQF,EAAQG,OAAOV,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,GAASA,EAAME,MACxBF,EAAME,KAAKC,QAAQ,SAACb,UAClBD,EAAkBC,EAAKC,EAAWC,EAAO,EAG/C,EATA,IAAK,IAAMD,KAAaO,EAAQG,OAAMF,EAAAR,EAUxC,ECAMa,EAAqB,SACzBC,EACAC,GAEA,IAAMC,EAAOC,EAAeF,GAC5B,OAAOD,EAAMI,KAAK,SAACC,GAAM,OAAAF,EAAeE,GAAGC,MAAK,IAAKJ,EAAI,UAAU,EACrE,EASA,SAASC,EAAeI,GACtB,OAAOA,EAAMC,QAAQ,SAAU,GACjC,sBA3C4B,SAC1BrB,EACAM,GAEAA,EAAQgB,2BAA6BjB,EAAuBL,EAAQM,GAEpE,IAAMiB,EAAc,CAA+B,EACnD,IAAK,IAAMR,KAAQf,EAAQ,CACzB,IAAMQ,EAAQN,EAAGA,IAACI,EAAQG,OAAQM,GAC5Bd,EAAQuB,OAAOC,OAAOzB,EAAOe,IAAS,GAAI,CAC9CjB,IAAKU,GAASA,EAAMV,MAGtB,GAAIc,EAAmBN,EAAQO,OAASW,OAAOE,KAAK1B,GAASe,GAAO,CAClE,IAAMY,EAAmBH,OAAOC,OAAO,CAAE,EAAEvB,EAAGA,IAACqB,EAAaR,IAE5Da,MAAID,EAAkB,OAAQ1B,GAC9B2B,MAAIL,EAAaR,EAAMY,EACzB,MACEC,EAAGA,IAACL,EAAaR,EAAMd,EAE3B,CAEA,OAAOsB,CACT"}
|
||||
2
node_modules/@hookform/resolvers/dist/resolvers.mjs
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/dist/resolvers.mjs
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{get as e,set as t}from"react-hook-form";const r=(t,r,o)=>{if(t&&"reportValidity"in t){const s=e(o,r);t.setCustomValidity(s&&s.message||""),t.reportValidity()}},o=(e,t)=>{for(const o in t.fields){const s=t.fields[o];s&&s.ref&&"reportValidity"in s.ref?r(s.ref,o,e):s&&s.refs&&s.refs.forEach(t=>r(t,o,e))}},s=(r,s)=>{s.shouldUseNativeValidation&&o(r,s);const n={};for(const o in r){const f=e(s.fields,o),c=Object.assign(r[o]||{},{ref:f&&f.ref});if(i(s.names||Object.keys(r),o)){const r=Object.assign({},e(n,o));t(r,"root",c),t(n,o,r)}else t(n,o,c)}return n},i=(e,t)=>{const r=n(t);return e.some(e=>n(e).match(`^${r}\\.\\d+`))};function n(e){return e.replace(/\]|\[/g,"")}export{s as toNestErrors,o as validateFieldsNatively};
|
||||
//# sourceMappingURL=resolvers.mjs.map
|
||||
1
node_modules/@hookform/resolvers/dist/resolvers.mjs.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/dist/resolvers.mjs.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"resolvers.mjs","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field && field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): FieldErrors<TFieldValues> => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors<TFieldValues>;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => {\n const path = escapeBrackets(name);\n return names.some((n) => escapeBrackets(n).match(`^${path}\\\\.\\\\d+`));\n};\n\n/**\n * Escapes special characters in a string to be used in a regex pattern.\n * it removes the brackets from the string to match the `set` method.\n *\n * @param input - The input string to escape.\n * @returns The escaped string.\n */\nfunction escapeBrackets(input: string): string {\n return input.replace(/\\]|\\[/g, '');\n}\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","fields","field","refs","forEach","toNestErrors","shouldUseNativeValidation","fieldErrors","path","Object","assign","isNameInFieldArray","names","keys","fieldArrayErrors","set","name","escapeBrackets","some","n","match","input","replace"],"mappings":"+CASA,MAAMA,EAAoBA,CACxBC,EACAC,EACAC,KAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,MAAMG,EAAQC,EAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,GAIWC,EAAyBA,CACpCL,EACAM,KAEA,IAAK,MAAMP,KAAaO,EAAQC,OAAQ,CACtC,MAAMC,EAAQF,EAAQC,OAAOR,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,GAASA,EAAMC,MACxBD,EAAMC,KAAKC,QAASZ,GAClBD,EAAkBC,EAAKC,EAAWC,GAGxC,GCzBWW,EAAeA,CAC1BX,EACAM,KAEAA,EAAQM,2BAA6BP,EAAuBL,EAAQM,GAEpE,MAAMO,EAAc,GACpB,IAAK,MAAMC,KAAQd,EAAQ,CACzB,MAAMQ,EAAQN,EAAII,EAAQC,OAAQO,GAC5Bb,EAAQc,OAAOC,OAAOhB,EAAOc,IAAS,CAAA,EAAI,CAC9ChB,IAAKU,GAASA,EAAMV,MAGtB,GAAImB,EAAmBX,EAAQY,OAASH,OAAOI,KAAKnB,GAASc,GAAO,CAClE,MAAMM,EAAmBL,OAAOC,OAAO,CAAA,EAAId,EAAIW,EAAaC,IAE5DO,EAAID,EAAkB,OAAQnB,GAC9BoB,EAAIR,EAAaC,EAAMM,EACzB,MACEC,EAAIR,EAAaC,EAAMb,EAE3B,CAEA,OAAOY,GAGHI,EAAqBA,CACzBC,EACAI,KAEA,MAAMR,EAAOS,EAAeD,GAC5B,OAAOJ,EAAMM,KAAMC,GAAMF,EAAeE,GAAGC,MAAM,IAAIZ,YAAc,EAUrE,SAASS,EAAeI,GACtB,OAAOA,EAAMC,QAAQ,SAAU,GACjC"}
|
||||
2
node_modules/@hookform/resolvers/dist/resolvers.module.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/dist/resolvers.module.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{get as r,set as e}from"react-hook-form";var t=function(e,t,i){if(e&&"reportValidity"in e){var n=r(i,t);e.setCustomValidity(n&&n.message||""),e.reportValidity()}},i=function(r,e){var i=function(i){var n=e.fields[i];n&&n.ref&&"reportValidity"in n.ref?t(n.ref,i,r):n&&n.refs&&n.refs.forEach(function(e){return t(e,i,r)})};for(var n in e.fields)i(n)},n=function(t,n){n.shouldUseNativeValidation&&i(t,n);var a={};for(var f in t){var s=r(n.fields,f),c=Object.assign(t[f]||{},{ref:s&&s.ref});if(o(n.names||Object.keys(t),f)){var u=Object.assign({},r(a,f));e(u,"root",c),e(a,f,u)}else e(a,f,c)}return a},o=function(r,e){var t=a(e);return r.some(function(r){return a(r).match("^"+t+"\\.\\d+")})};function a(r){return r.replace(/\]|\[/g,"")}export{n as toNestErrors,i as validateFieldsNatively};
|
||||
//# sourceMappingURL=resolvers.module.js.map
|
||||
1
node_modules/@hookform/resolvers/dist/resolvers.module.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/dist/resolvers.module.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"resolvers.module.js","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field && field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): FieldErrors<TFieldValues> => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors<TFieldValues>;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => {\n const path = escapeBrackets(name);\n return names.some((n) => escapeBrackets(n).match(`^${path}\\\\.\\\\d+`));\n};\n\n/**\n * Escapes special characters in a string to be used in a regex pattern.\n * it removes the brackets from the string to match the `set` method.\n *\n * @param input - The input string to escape.\n * @returns The escaped string.\n */\nfunction escapeBrackets(input: string): string {\n return input.replace(/\\]|\\[/g, '');\n}\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","_loop","field","fields","refs","forEach","toNestErrors","shouldUseNativeValidation","fieldErrors","path","Object","assign","isNameInFieldArray","names","keys","fieldArrayErrors","set","name","escapeBrackets","some","n","match","input","replace"],"mappings":"+CASA,IAAMA,EAAoB,SACxBC,EACAC,EACAC,GAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,IAAMG,EAAQC,EAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,CACF,EAGaC,EAAyB,SACpCL,EACAM,GACQC,IAAAA,WAAAR,GAEN,IAAMS,EAAQF,EAAQG,OAAOV,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,GAASA,EAAME,MACxBF,EAAME,KAAKC,QAAQ,SAACb,UAClBD,EAAkBC,EAAKC,EAAWC,EAAO,EAG/C,EATA,IAAK,IAAMD,KAAaO,EAAQG,OAAMF,EAAAR,EAUxC,EC1Baa,EAAe,SAC1BZ,EACAM,GAEAA,EAAQO,2BAA6BR,EAAuBL,EAAQM,GAEpE,IAAMQ,EAAc,CAA+B,EACnD,IAAK,IAAMC,KAAQf,EAAQ,CACzB,IAAMQ,EAAQN,EAAII,EAAQG,OAAQM,GAC5Bd,EAAQe,OAAOC,OAAOjB,EAAOe,IAAS,GAAI,CAC9CjB,IAAKU,GAASA,EAAMV,MAGtB,GAAIoB,EAAmBZ,EAAQa,OAASH,OAAOI,KAAKpB,GAASe,GAAO,CAClE,IAAMM,EAAmBL,OAAOC,OAAO,CAAE,EAAEf,EAAIY,EAAaC,IAE5DO,EAAID,EAAkB,OAAQpB,GAC9BqB,EAAIR,EAAaC,EAAMM,EACzB,MACEC,EAAIR,EAAaC,EAAMd,EAE3B,CAEA,OAAOa,CACT,EAEMI,EAAqB,SACzBC,EACAI,GAEA,IAAMR,EAAOS,EAAeD,GAC5B,OAAOJ,EAAMM,KAAK,SAACC,GAAM,OAAAF,EAAeE,GAAGC,MAAK,IAAKZ,EAAI,UAAU,EACrE,EASA,SAASS,EAAeI,GACtB,OAAOA,EAAMC,QAAQ,SAAU,GACjC"}
|
||||
2
node_modules/@hookform/resolvers/dist/resolvers.umd.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/dist/resolvers.umd.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","react-hook-form"],t):t((e||self).hookformResolvers={},e.ReactHookForm)}(this,function(e,t){var r=function(e,r,o){if(e&&"reportValidity"in e){var i=t.get(o,r);e.setCustomValidity(i&&i.message||""),e.reportValidity()}},o=function(e,t){var o=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?r(i.ref,o,e):i&&i.refs&&i.refs.forEach(function(t){return r(t,o,e)})};for(var i in t.fields)o(i)},i=function(e,t){var r=n(t);return e.some(function(e){return n(e).match("^"+r+"\\.\\d+")})};function n(e){return e.replace(/\]|\[/g,"")}e.toNestErrors=function(e,r){r.shouldUseNativeValidation&&o(e,r);var n={};for(var f in e){var s=t.get(r.fields,f),a=Object.assign(e[f]||{},{ref:s&&s.ref});if(i(r.names||Object.keys(e),f)){var u=Object.assign({},t.get(n,f));t.set(u,"root",a),t.set(n,f,u)}else t.set(n,f,a)}return n},e.validateFieldsNatively=o});
|
||||
//# sourceMappingURL=resolvers.umd.js.map
|
||||
1
node_modules/@hookform/resolvers/dist/resolvers.umd.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/dist/resolvers.umd.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"resolvers.umd.js","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field && field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): FieldErrors<TFieldValues> => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors<TFieldValues>;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => {\n const path = escapeBrackets(name);\n return names.some((n) => escapeBrackets(n).match(`^${path}\\\\.\\\\d+`));\n};\n\n/**\n * Escapes special characters in a string to be used in a regex pattern.\n * it removes the brackets from the string to match the `set` method.\n *\n * @param input - The input string to escape.\n * @returns The escaped string.\n */\nfunction escapeBrackets(input: string): string {\n return input.replace(/\\]|\\[/g, '');\n}\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","_loop","field","fields","refs","forEach","isNameInFieldArray","names","name","path","escapeBrackets","some","n","match","input","replace","shouldUseNativeValidation","fieldErrors","Object","assign","keys","fieldArrayErrors","set"],"mappings":"0SASA,IAAMA,EAAoB,SACxBC,EACAC,EACAC,GAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,IAAMG,EAAQC,MAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,CACF,EAGaC,EAAyB,SACpCL,EACAM,GACQC,IAAAA,WAAAR,GAEN,IAAMS,EAAQF,EAAQG,OAAOV,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,GAASA,EAAME,MACxBF,EAAME,KAAKC,QAAQ,SAACb,UAClBD,EAAkBC,EAAKC,EAAWC,EAAO,EAG/C,EATA,IAAK,IAAMD,KAAaO,EAAQG,OAAMF,EAAAR,EAUxC,ECAMa,EAAqB,SACzBC,EACAC,GAEA,IAAMC,EAAOC,EAAeF,GAC5B,OAAOD,EAAMI,KAAK,SAACC,GAAM,OAAAF,EAAeE,GAAGC,MAAK,IAAKJ,EAAI,UAAU,EACrE,EASA,SAASC,EAAeI,GACtB,OAAOA,EAAMC,QAAQ,SAAU,GACjC,gBA3C4B,SAC1BrB,EACAM,GAEAA,EAAQgB,2BAA6BjB,EAAuBL,EAAQM,GAEpE,IAAMiB,EAAc,CAA+B,EACnD,IAAK,IAAMR,KAAQf,EAAQ,CACzB,IAAMQ,EAAQN,EAAGA,IAACI,EAAQG,OAAQM,GAC5Bd,EAAQuB,OAAOC,OAAOzB,EAAOe,IAAS,GAAI,CAC9CjB,IAAKU,GAASA,EAAMV,MAGtB,GAAIc,EAAmBN,EAAQO,OAASW,OAAOE,KAAK1B,GAASe,GAAO,CAClE,IAAMY,EAAmBH,OAAOC,OAAO,CAAE,EAAEvB,EAAGA,IAACqB,EAAaR,IAE5Da,MAAID,EAAkB,OAAQ1B,GAC9B2B,MAAIL,EAAaR,EAAMY,EACzB,MACEC,EAAGA,IAACL,EAAaR,EAAMd,EAE3B,CAEA,OAAOsB,CACT"}
|
||||
2
node_modules/@hookform/resolvers/dist/toNestErrors.d.ts
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/dist/toNestErrors.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import { FieldErrors, FieldValues, ResolverOptions } from 'react-hook-form';
|
||||
export declare const toNestErrors: <TFieldValues extends FieldValues>(errors: FieldErrors, options: ResolverOptions<TFieldValues>) => FieldErrors<TFieldValues>;
|
||||
2
node_modules/@hookform/resolvers/dist/validateFieldsNatively.d.ts
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/dist/validateFieldsNatively.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import { FieldErrors, FieldValues, ResolverOptions } from 'react-hook-form';
|
||||
export declare const validateFieldsNatively: <TFieldValues extends FieldValues>(errors: FieldErrors, options: ResolverOptions<TFieldValues>) => void;
|
||||
11
node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.d.ts
generated
vendored
Normal file
11
node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import { Schema } from 'effect';
|
||||
import { ParseOptions } from 'effect/SchemaAST';
|
||||
import { FieldValues, Resolver } from 'react-hook-form';
|
||||
export declare function effectTsResolver<Input extends FieldValues, Context, Output>(schema: Schema.Schema<Output, Input>, schemaOptions?: ParseOptions, resolverOptions?: {
|
||||
mode?: 'async' | 'sync';
|
||||
raw?: false;
|
||||
}): Resolver<Input, Context, Output>;
|
||||
export declare function effectTsResolver<Input extends FieldValues, Context, Output>(schema: Schema.Schema<Output, Input>, schemaOptions: ParseOptions | undefined, resolverOptions: {
|
||||
mode?: 'async' | 'sync';
|
||||
raw: true;
|
||||
}): Resolver<Input, Context, Input>;
|
||||
2
node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.js
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
var e=require("@hookform/resolvers"),r=require("effect"),t=require("effect/ParseResult"),o=require("react-hook-form");exports.effectTsResolver=function(n,a){return void 0===a&&(a={errors:"all",onExcessProperty:"ignore"}),function(s,f,i){return t.decodeUnknown(n,a)(s).pipe(r.Effect.catchAll(function(e){return r.Effect.flip(t.ArrayFormatter.formatIssue(e))}),r.Effect.mapError(function(r){var t=!i.shouldUseNativeValidation&&"all"===i.criteriaMode,n=r.reduce(function(e,r){var n=r.path.join(".");if(e[n]||(e[n]={message:r.message,type:r._tag}),t){var a=e[n].types,s=a&&a[String(r._tag)];e[n]=o.appendErrors(n,t,e,r._tag,s?[].concat(s,r.message):r.message)}return e},{});return e.toNestErrors(n,i)}),r.Effect.tap(function(){return r.Effect.sync(function(){return i.shouldUseNativeValidation&&e.validateFieldsNatively({},i)})}),r.Effect.match({onFailure:function(e){return{errors:e,values:{}}},onSuccess:function(e){return{errors:{},values:e}}}),r.Effect.runPromise)}};
|
||||
//# sourceMappingURL=effect-ts.js.map
|
||||
1
node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.js.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.js.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"effect-ts.js","sources":["../src/effect-ts.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { Effect, Schema } from 'effect';\nimport { ArrayFormatter, decodeUnknown } from 'effect/ParseResult';\nimport { ParseOptions } from 'effect/SchemaAST';\nimport {\n type FieldError,\n FieldValues,\n Resolver,\n appendErrors,\n} from 'react-hook-form';\n\nexport function effectTsResolver<Input extends FieldValues, Context, Output>(\n schema: Schema.Schema<Output, Input>,\n schemaOptions?: ParseOptions,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver<Input, Context, Output>;\n\nexport function effectTsResolver<Input extends FieldValues, Context, Output>(\n schema: Schema.Schema<Output, Input>,\n schemaOptions: ParseOptions | undefined,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver<Input, Context, Input>;\n\n/**\n * Creates a resolver for react-hook-form using Effect.ts schema validation\n * @param {Schema.Schema<TFieldValues, I>} schema - The Effect.ts schema to validate against\n * @param {ParseOptions} [schemaOptions] - Optional Effect.ts validation options\n * @returns {Resolver<Schema.Schema.Type<typeof schema>>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema.Struct({\n * name: Schema.String,\n * age: Schema.Number\n * });\n *\n * useForm({\n * resolver: effectTsResolver(schema)\n * });\n */\nexport function effectTsResolver<Input extends FieldValues, Context, Output>(\n schema: Schema.Schema<Output, Input>,\n schemaOptions: ParseOptions = { errors: 'all', onExcessProperty: 'ignore' },\n): Resolver<Input, Context, Output | Input> {\n return (values, _, options) => {\n return decodeUnknown(\n schema,\n schemaOptions,\n )(values).pipe(\n Effect.catchAll((parseIssue) =>\n Effect.flip(ArrayFormatter.formatIssue(parseIssue)),\n ),\n Effect.mapError((issues) => {\n const validateAllFieldCriteria =\n !options.shouldUseNativeValidation && options.criteriaMode === 'all';\n\n const errors = issues.reduce(\n (acc, error) => {\n const key = error.path.join('.');\n\n if (!acc[key]) {\n acc[key] = { message: error.message, type: error._tag };\n }\n\n if (validateAllFieldCriteria) {\n const types = acc[key].types;\n const messages = types && types[String(error._tag)];\n\n acc[key] = appendErrors(\n key,\n validateAllFieldCriteria,\n acc,\n error._tag,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n return acc;\n },\n {} as Record<string, FieldError>,\n );\n\n return toNestErrors(errors, options);\n }),\n Effect.tap(() =>\n Effect.sync(\n () =>\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options),\n ),\n ),\n Effect.match({\n onFailure: (errors) => ({ errors, values: {} }),\n onSuccess: (result) => ({ errors: {}, values: result }),\n }),\n Effect.runPromise,\n );\n };\n}\n"],"names":["schema","schemaOptions","errors","onExcessProperty","values","_","options","decodeUnknown","pipe","Effect","catchAll","parseIssue","flip","ArrayFormatter","formatIssue","mapError","issues","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","reduce","acc","error","key","path","join","message","type","_tag","types","messages","String","appendErrors","concat","toNestErrors","tap","sync","validateFieldsNatively","match","onFailure","onSuccess","result","runPromise"],"mappings":"+IA4CgB,SACdA,EACAC,GAEA,YAFAA,IAAAA,IAAAA,EAA8B,CAAEC,OAAQ,MAAOC,iBAAkB,WAE1D,SAACC,EAAQC,EAAGC,GACjB,OAAOC,EAAaA,cAClBP,EACAC,EAFKM,CAGLH,GAAQI,KACRC,EAAMA,OAACC,SAAS,SAACC,GACf,OAAAF,SAAOG,KAAKC,EAAAA,eAAeC,YAAYH,GAAY,GAErDF,EAAAA,OAAOM,SAAS,SAACC,GACf,IAAMC,GACHX,EAAQY,2BAAsD,QAAzBZ,EAAQa,aAE1CjB,EAASc,EAAOI,OACpB,SAACC,EAAKC,GACJ,IAAMC,EAAMD,EAAME,KAAKC,KAAK,KAM5B,GAJKJ,EAAIE,KACPF,EAAIE,GAAO,CAAEG,QAASJ,EAAMI,QAASC,KAAML,EAAMM,OAG/CX,EAA0B,CAC5B,IAAMY,EAAQR,EAAIE,GAAKM,MACjBC,EAAWD,GAASA,EAAME,OAAOT,EAAMM,OAE7CP,EAAIE,GAAOS,EAAYA,aACrBT,EACAN,EACAI,EACAC,EAAMM,KACNE,EACK,GAAgBG,OAAOH,EAAsBR,EAAMI,SACpDJ,EAAMI,QAEd,CAEA,OAAOL,CACT,EACA,CAAgC,GAGlC,OAAOa,eAAahC,EAAQI,EAC9B,GACAG,EAAAA,OAAO0B,IAAI,WAAA,OACT1B,EAAAA,OAAO2B,KACL,kBACE9B,EAAQY,2BACRmB,EAAsBA,uBAAC,GAAI/B,EAAQ,EACtC,GAEHG,EAAAA,OAAO6B,MAAM,CACXC,UAAW,SAACrC,GAAM,MAAM,CAAEA,OAAAA,EAAQE,OAAQ,GAAI,EAC9CoC,UAAW,SAACC,GAAY,MAAA,CAAEvC,OAAQ,CAAA,EAAIE,OAAQqC,EAAQ,IAExDhC,EAAAA,OAAOiC,WAEX,CACF"}
|
||||
2
node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.mjs
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.mjs
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{Effect as t}from"effect";import{decodeUnknown as o,ArrayFormatter as n}from"effect/ParseResult";import{appendErrors as a}from"react-hook-form";function i(i,s){return void 0===s&&(s={errors:"all",onExcessProperty:"ignore"}),function(u,c,f){return o(i,s)(u).pipe(t.catchAll(function(r){return t.flip(n.formatIssue(r))}),t.mapError(function(e){var t=!f.shouldUseNativeValidation&&"all"===f.criteriaMode,o=e.reduce(function(r,e){var o=e.path.join(".");if(r[o]||(r[o]={message:e.message,type:e._tag}),t){var n=r[o].types,i=n&&n[String(e._tag)];r[o]=a(o,t,r,e._tag,i?[].concat(i,e.message):e.message)}return r},{});return r(o,f)}),t.tap(function(){return t.sync(function(){return f.shouldUseNativeValidation&&e({},f)})}),t.match({onFailure:function(r){return{errors:r,values:{}}},onSuccess:function(r){return{errors:{},values:r}}}),t.runPromise)}}export{i as effectTsResolver};
|
||||
//# sourceMappingURL=effect-ts.module.js.map
|
||||
2
node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.modern.mjs
generated
vendored
Normal file
2
node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.modern.mjs
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import{toNestErrors as e,validateFieldsNatively as r}from"@hookform/resolvers";import{Effect as o}from"effect";import{decodeUnknown as t,ArrayFormatter as s}from"effect/ParseResult";import{appendErrors as a}from"react-hook-form";function i(i,n={errors:"all",onExcessProperty:"ignore"}){return(c,m,l)=>t(i,n)(c).pipe(o.catchAll(e=>o.flip(s.formatIssue(e))),o.mapError(r=>{const o=!l.shouldUseNativeValidation&&"all"===l.criteriaMode,t=r.reduce((e,r)=>{const t=r.path.join(".");if(e[t]||(e[t]={message:r.message,type:r._tag}),o){const s=e[t].types,i=s&&s[String(r._tag)];e[t]=a(t,o,e,r._tag,i?[].concat(i,r.message):r.message)}return e},{});return e(t,l)}),o.tap(()=>o.sync(()=>l.shouldUseNativeValidation&&r({},l))),o.match({onFailure:e=>({errors:e,values:{}}),onSuccess:e=>({errors:{},values:e})}),o.runPromise)}export{i as effectTsResolver};
|
||||
//# sourceMappingURL=effect-ts.modern.mjs.map
|
||||
1
node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.modern.mjs.map
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/effect-ts/dist/effect-ts.modern.mjs.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"effect-ts.modern.mjs","sources":["../src/effect-ts.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { Effect, Schema } from 'effect';\nimport { ArrayFormatter, decodeUnknown } from 'effect/ParseResult';\nimport { ParseOptions } from 'effect/SchemaAST';\nimport {\n type FieldError,\n FieldValues,\n Resolver,\n appendErrors,\n} from 'react-hook-form';\n\nexport function effectTsResolver<Input extends FieldValues, Context, Output>(\n schema: Schema.Schema<Output, Input>,\n schemaOptions?: ParseOptions,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver<Input, Context, Output>;\n\nexport function effectTsResolver<Input extends FieldValues, Context, Output>(\n schema: Schema.Schema<Output, Input>,\n schemaOptions: ParseOptions | undefined,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver<Input, Context, Input>;\n\n/**\n * Creates a resolver for react-hook-form using Effect.ts schema validation\n * @param {Schema.Schema<TFieldValues, I>} schema - The Effect.ts schema to validate against\n * @param {ParseOptions} [schemaOptions] - Optional Effect.ts validation options\n * @returns {Resolver<Schema.Schema.Type<typeof schema>>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema.Struct({\n * name: Schema.String,\n * age: Schema.Number\n * });\n *\n * useForm({\n * resolver: effectTsResolver(schema)\n * });\n */\nexport function effectTsResolver<Input extends FieldValues, Context, Output>(\n schema: Schema.Schema<Output, Input>,\n schemaOptions: ParseOptions = { errors: 'all', onExcessProperty: 'ignore' },\n): Resolver<Input, Context, Output | Input> {\n return (values, _, options) => {\n return decodeUnknown(\n schema,\n schemaOptions,\n )(values).pipe(\n Effect.catchAll((parseIssue) =>\n Effect.flip(ArrayFormatter.formatIssue(parseIssue)),\n ),\n Effect.mapError((issues) => {\n const validateAllFieldCriteria =\n !options.shouldUseNativeValidation && options.criteriaMode === 'all';\n\n const errors = issues.reduce(\n (acc, error) => {\n const key = error.path.join('.');\n\n if (!acc[key]) {\n acc[key] = { message: error.message, type: error._tag };\n }\n\n if (validateAllFieldCriteria) {\n const types = acc[key].types;\n const messages = types && types[String(error._tag)];\n\n acc[key] = appendErrors(\n key,\n validateAllFieldCriteria,\n acc,\n error._tag,\n messages\n ? ([] as string[]).concat(messages as string[], error.message)\n : error.message,\n ) as FieldError;\n }\n\n return acc;\n },\n {} as Record<string, FieldError>,\n );\n\n return toNestErrors(errors, options);\n }),\n Effect.tap(() =>\n Effect.sync(\n () =>\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options),\n ),\n ),\n Effect.match({\n onFailure: (errors) => ({ errors, values: {} }),\n onSuccess: (result) => ({ errors: {}, values: result }),\n }),\n Effect.runPromise,\n );\n };\n}\n"],"names":["effectTsResolver","schema","schemaOptions","errors","onExcessProperty","values","_","options","decodeUnknown","pipe","Effect","catchAll","parseIssue","flip","ArrayFormatter","formatIssue","mapError","issues","validateAllFieldCriteria","shouldUseNativeValidation","criteriaMode","reduce","acc","error","key","path","join","message","type","_tag","types","messages","String","appendErrors","concat","toNestErrors","tap","sync","validateFieldsNatively","match","onFailure","onSuccess","result","runPromise"],"mappings":"8OA4CgBA,EACdC,EACAC,EAA8B,CAAEC,OAAQ,MAAOC,iBAAkB,WAEjE,MAAO,CAACC,EAAQC,EAAGC,IACVC,EACLP,EACAC,EAFKM,CAGLH,GAAQI,KACRC,EAAOC,SAAUC,GACfF,EAAOG,KAAKC,EAAeC,YAAYH,KAEzCF,EAAOM,SAAUC,IACf,MAAMC,GACHX,EAAQY,2BAAsD,QAAzBZ,EAAQa,aAE1CjB,EAASc,EAAOI,OACpB,CAACC,EAAKC,KACJ,MAAMC,EAAMD,EAAME,KAAKC,KAAK,KAM5B,GAJKJ,EAAIE,KACPF,EAAIE,GAAO,CAAEG,QAASJ,EAAMI,QAASC,KAAML,EAAMM,OAG/CX,EAA0B,CAC5B,MAAMY,EAAQR,EAAIE,GAAKM,MACjBC,EAAWD,GAASA,EAAME,OAAOT,EAAMM,OAE7CP,EAAIE,GAAOS,EACTT,EACAN,EACAI,EACAC,EAAMM,KACNE,EACK,GAAgBG,OAAOH,EAAsBR,EAAMI,SACpDJ,EAAMI,QAEd,CAEA,OAAOL,GAET,CAAgC,GAGlC,OAAOa,EAAahC,EAAQI,EAAO,GAErCG,EAAO0B,IAAI,IACT1B,EAAO2B,KACL,IACE9B,EAAQY,2BACRmB,EAAuB,CAAA,EAAI/B,KAGjCG,EAAO6B,MAAM,CACXC,UAAYrC,IAAY,CAAEA,SAAQE,OAAQ,KAC1CoC,UAAYC,IAAY,CAAEvC,OAAQ,CAAE,EAAEE,OAAQqC,MAEhDhC,EAAOiC,WAGb"}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue