Giter VIP home page Giter VIP logo

react-hook-form / resolvers Goto Github PK

View Code? Open in Web Editor NEW
1.6K 11.0 138.0 2.07 MB

๐Ÿ“‹ Validation resolvers: Yup, Zod, AJV, Joi, Superstruct, Vest, class-validator, io-ts, typanion, Ajv, TypeBox, Valibot and nope.

Home Page: https://react-hook-form.com/

License: MIT License

JavaScript 0.99% TypeScript 98.97% Shell 0.04%
yup superstruct joi form form-validation hooks validation schema-validation resolvers typescript

resolvers's Introduction

npm downloads npm npm Discord

Get started | API | Form Builder | FAQs | Examples

Features

Install

npm install react-hook-form

Quickstart

import { useForm } from 'react-hook-form';

function App() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

  return (
    <form onSubmit={handleSubmit((data) => console.log(data))}>
      <input {...register('firstName')} />
      <input {...register('lastName', { required: true })} />
      {errors.lastName && <p>Last name is required.</p>}
      <input {...register('age', { pattern: /\d+/ })} />
      {errors.age && <p>Please enter number for age.</p>}
      <input type="submit" />
    </form>
  );
}

Sponsors

Thanks go to these kind and lovely sponsors!

Past sponsors

Backers

Thanks go to all our backers! [Become a backer].

Contributors

Thanks go to these wonderful people! [Become a contributor].

resolvers's People

Contributors

adamward459 avatar aprilrd avatar arcanis avatar benallfree avatar bluebill1049 avatar dearlordylord avatar dependabot[bot] avatar github-actions[bot] avatar grsmto avatar hlubek avatar impl avatar jorisre avatar katt avatar kotarella1110 avatar mdornseif avatar mexvod avatar moonou avatar mzalevski avatar norkin avatar ogbeche77 avatar paul-vandell avatar perebusquets avatar richardvanbergen avatar robintail avatar ryomasao avatar ryota-ka avatar sangjunbak avatar stramel avatar thedscpl avatar zebapy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

resolvers's Issues

Failed to parse source map + IE11

Running latest version 1.0.0 I get these complications:

Failed to parse source map .../node_modules/@hookform/resolvers/src/yup.ts'
file: Error: ENOENT: no such file or directory, open '.../react-app/node_modules/@hookform/resolvers/src/yup.ts'

Also can you provide example of how using it with IE11 in documentation?
Should it be like this?

import { yupResolver } from '@hookform/resolvers/dist/ie11/yup';

When using it with IE11 I get this:
image

Feature request: support synchronous validation

We are using yup along with react-hook-form, and almost all of our schemata support synchronous validation. Unfortunately, there's no way to use schema.validateSync instead of schema.validate through the resolver.

While the performance impact of this is negligible, inserting an event loop between form submission and handleSubmit being called adds an unnecessary layer of complexity to our tests.

It would be great if we could pass an option to validate the schema synchronously. Better yet, if the resolver attempted to validate synchronously and fell back on asynchronous validation if required.

Yup resolver problem with test function

Hello,

It seems there is a problem with the yupResolver, when there is a schema with test function.

This a CodeSandbox to reproduce the problem: https://codesandbox.io/s/yup-resolver-problem-with-yup-test-function-16r4d?file=/src/App.js

The form example has 3 inputs. The age is required, only here to illustrate that individual field can throw, as expected, an error.
But the test function, which checks if email or name are present, does not throw a ValidationError.

The onSubmit method shows that there is no error and that the data is an empty object. ๐Ÿ˜ข

Import error: 'appendErrors'

I seem to have this issue come up and I have no idea what is causing it.

./node_modules/@hookform/resolvers/dist/index.esm.js
Attempted import error: 'appendErrors' is not exported from 'react-hook-form'.

Error is not cleared after selecting a value

Describe the bug
I am using react-hook-forms alongside with Material-ui and yup.
With the select, I have an error, when you submit first then you change the value, the error is not cleared.

To Reproduce
Steps to reproduce the behavior:

  • Click on submit (do not select a value) the error is displayed => Ok!
  • Select a value => Error is not cleared => NOK

Codesandbox link (Required)
https://codesandbox.io/s/react-hook-form-mui-yup-2ect1?file=/demo.tsx

Expected behavior
Error should be cleared when you select a new value.

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser chrome
  • Version: 85 (latest)

Question: How to do multiple checks for password validation with Yup and RFH?

I am wondering if there is a way with yup and yupResolver with RHF to do something similar to this:

https://codesandbox.io/s/eager-bush-dfl5t

Basically using this code when a user starts typing into the password field you get separated booleans for each validation criteria which allows you to build an interactive component such as:

Screen Shot 2020-07-13 at 7 40 26 PM

Code that I have been playing around with:

....
import { yupResolver } from '@hookform/resolvers';

const passwordSchema = yup.object().shape({
  password: yup
    .string()
    .required()
    .min(8)
    .matches(RegExp('(.*[a-z].*)'), 'Lowercase')
    .matches(RegExp('(.*[A-Z].*)'), 'Uppercase')
    .matches(RegExp('(.*\\d.*)'), 'Number')
    .matches(RegExp('[!@#$%^&*(),.?":{}|<>]'), 'Special'),
});

  const { register, handleSubmit, errors, formState, getValues } = useForm({
    resolver: yupResolver(
      passwordSchema
    ),
    criteriaMode: 'all',
    reValidateMode: 'onChange',
    mode: 'onChange',
  });
....

Which results in:

Screen Shot 2020-07-13 at 7 47 39 PM

I was hoping to have types returned like the coding sample so I can flag the realtime critera.

Any help or things in yup would be super helpful.

Thanks!

Build error after upgrade to 1.3.1 in Next.js

Hi guys,

I have an SSR app working on Node environments, after upgrade to 1.3.1 and build error:

[2020-12-31T02:56:35.428Z] #16 90.33 > Build error occurred
[2020-12-31T02:56:35.428Z] #16 90.34 /app/node_modules/@hookform/resolvers/dist/yup.js:2
[2020-12-31T02:56:35.428Z] #16 90.34 import { transformToNestObject, } from 'react-hook-form';
[2020-12-31T02:56:35.428Z] #16 90.34 ^^^^^^
[2020-12-31T02:56:35.428Z] #16 90.34
[2020-12-31T02:56:35.428Z] #16 90.34 SyntaxError: Cannot use import statement outside a module
[2020-12-31T02:56:35.428Z] #16 90.34 at wrapSafe (node:internal/modules/cjs/loader:1024:16)
[2020-12-31T02:56:35.428Z] #16 90.34 at Module._compile (node:internal/modules/cjs/loader:1072:27)

I think the problem related to #95 PR.

@hookform/resolvers doesn't work with IE11

Hi, although there is a transpiled module, it still doesn't work with IE11.

Resolver imported from the transpiled module:
import { yupResolver } from '@hookform/resolvers/dist/index.ie11';

Error:

/node_modules/@hookform/resolvers/dist/index.ie11.js:1
import { transformToNestObject, appendErrors } from 'react-hook-form';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at compileFunction ()
at Module._compile (internal/modules/cjs/loader.js:892:18)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:849:19)
at require (internal/modules/cjs/helpers.js:74:18)

Tried in Next.js project.

yupResolver fails to validate an uncontrolled field that depends on a controlled field value.

Hi!

I hope you can help me solve the problem i'm facing.

I am trying to add validation rules to an uncontrolled field, based on the value of a controlled select (in my case a react-select).
When the value of the select changes to a particular value (in this case 'yes'), the other field needs get the required validation rule added.

Sandbox example: https://codesandbox.io/s/react-hook-form-yup-validation-crhzk

How to reproduce

  • Switch the 'controlled' select to the value 'Yes'
  • Hit the 'submit' button.

What i expected

  • The 'Uncontrolled' field should be required.
  • An error message should be displayed in the console.

What happens

Could you tell me what i'm doing wrong?

Nested yup schema validation

I'm currently migrating to react-hook-form and the current yup resolver does recognise yup's when in nested schemas.

I've created an example here. You should be able to submit the form because the condition has been met, but the resolver doesn't recognise it?

Love the work that you're doing! Thanks in advance for your help!

Uncaught ReferenceError: exports is not defined

trying to:

import { zodResolver } from "@hookform/resolvers/zod";

gives me:

Uncaught ReferenceError: exports is not defined
    at Module../node_modules/@hookform/resolvers/dist/zod.js (zod.js:11)
    at __webpack_require__ (bootstrap:789)
    at fn (bootstrap:100)
    at Object../node_modules/@hookform/resolvers/zod.js (zod.js:1)
    at __webpack_require__ (bootstrap:789)
    at fn (bootstrap:100)
    ...

This is a Rails webpacker + typescript app.

Yup ValidationError is leaking and becomes untracked runtime error

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
To reproduce add test call to any yup field here is an example yup schema

const SignupSchema = yup.object().shape({
  firstName: yup.string().required(),
  age: yup.number().required().positive().integer(),
  username: yup
    .string()
    .required("Please enter your username.")
    .min(6, "Username must be between 6 and 30 characters long")
    .max(30, "Username must be between 6 and 30 characters long")
    .test(
      "un-is-username",
      "Username must not be your email address",
      (value) => {
        if (!value || !yup.ref("firstName")) {
          return true;
        }
        return !value.contains(yup.ref("firstName"));
      }
    )
    .test("un-availability", "Username availability check", async function (
      value
    ) {
      console.log("availability check...");
      if (!value) {
        return true;
      }
      const response = validateUsername(value);
      if (response.status) {
        return true;
      }
      return this.createError({ path: this.path, message: response.error });
    }),
  website: yup.string().url()
});
  1. Go to codesandbox link
  2. Fill first name, last name and put abc or any non valid string into username field
  3. Click Submit button
  4. See error

image

Codesandbox link (Required)
I used ValidationSchema example as a base and added username field

Expected behavior
I expect to error to be catched and processed as any other errors

Library versions
"react": "16.13.1",
"react-dom": "16.13.1",
"react-hook-form": "^6.5.1",
"yup": "^0.29.3",
"@hookform/resolvers": "^0.1.0" <-- i think the problem is here, but can't understand what's wrong in the code

Ref not propagating to errors object when resolver is used

Hello react-hook-form,

First of all, thank you for a great form library! However, I am noticing an issue with propagating the ref of the input that threw the error when I use the Joi resolver in my project.

According to the docs here: https://react-hook-form.com/api#errors I should receive type, types, message and ref from the errors object. I have confirmed that this is true when I don't use a resolver and construct my field validation manually like so:

console.log(errors);

<input
  ref={register({ required: 'custom required message' })}
  type="email"
  name="email"
  ...etc.
/>

Screen Shot 2020-11-16 at 11 56 19 AM

...but when I construct my field validations via Joi I only receive the message and type properties from the errors object. My code looks something like this:

const { register, errors } = useForm<FormValues>({
  resolver: joiResolver(validationSchema.current),
});

console.log(errors);

<input
  ref={register}
  type="email"
  name="email"
  ...etc.
/>

...and my response looks like this:
Screen Shot 2020-11-16 at 11 55 28 AM

How do I ensure that the ref of the input which threw the error comes through in the useForm errors object?

Thanks for your help!

tsconfig changes required to use resolvers

I'm migrating from v5 to v6 with resolvers. I'm getting Typescript errors when I try to build my project which required changing my tsconfig.json

xxx/node_modules/@hookform/resolvers/dist/superstruct.d.ts
(2,8): Module '"xxxx/node_modules/superstruct/lib/index"' has no default export.

and

xxx/node_modules/@hookform/resolvers/dist/superstruct.d.ts
(3,94): Generic type 'Struct<T, S>' requires between 1 and 2 type arguments.

( xxx is truncated path to my project folder)

For the first one I had to add this to my tsconfig.json

"allowSyntheticDefaultImports": true

and for the second I had to edit node_modules/@hookform/resolvers/dist/superstruct.d.ts to put a

// @ts-ignore

between lines 2 and 3

Cannot resolve symbol 'yupResolver'

Hey, I'm trying to import yupResolver in my project, where I'm using Typescript but I'm getting this error:
Cannot resolve symbol 'yupResolver'

I'm importing yupResolver like this:
import { yupResolver } from '@hookform/resolvers/yup';

Is there something that I'm doing wrong?

Version of @hookform/resolvers: 1.1.2
Version of react-hook-form: 6.12.2
Version of Yup: 0.32.8

Zod resolver with typescript not working

image

My schema is as follows

const schema = z.object({
  flag: z.object({
    label: z.string(),
    value: z.string()
  }),
  reason: z.string()
})

type Flag = z.infer<typeof schema.shape.flag>
type AddFlag = z.infer<typeof schema>

Yup validation schema does not work with nested objects

I modified the yup schema validation example to use nested objects. However validations are not working for nested objects.

Please see my CodeSandbox

I know there was a related issue (react-hook-form/react-hook-form#893) in January, however I am not sure if it was fixed.

I am using the latest versions except for @hookform/resolvers. Looks like v1.00 has some API changes, so reverted back to v0.0.3 which was used in the original example.

My project uses nested objects very heavily, so it is important to get this working. Please help!

Type error in yup resolver

Hi everyone. Thank you for a great tool.
I tried to use yup resolver with typescript. But i faced with typescript compilation error.

i ๏ฝขwdm๏ฝฃ: Compiled with warnings.
ERROR in D:/Repositories/form/node_modules/@hookform/resolvers/dist/yup.d.ts(3,86):
TS2707: Generic type 'ObjectSchema<TShape, TContext, TIn, TOut>' requires between 1 and 4 type arguments.

ERROR in D:/Repositories/form/node_modules/@hookform/resolvers/dist/yup.d.ts(3,109):
TS2694: Namespace '"D:/Repositories/form/node_modules/yup/lib/index"' has no exported member 'Lazy'.

ERROR in D:/Repositories/form/node_modules/@hookform/resolvers/dist/yup.d.ts(3,134):
TS2694: Namespace '"D:/Repositories/form/node_modules/yup/lib/index"' has no exported member 'ValidateOptions'.

My packages:
"yup": "^0.32.5"
"react-hook-form": "^6.12.2",
"@hookform/resolvers": "^1.1.1",

I tried to use @types/yup but it doesnt help to me
"@types/yup": "^0.29.10",

Can anybody to help me?
How i can to fix this issue?

Module not found: Can't resolve 'react-hook-form-resolvers'

Install the module using yarn add react-hook-form-resolvers.

Then import yupResolver.

import { yupResolver } from 'react-hook-form-resolvers

I am getting
Module not found: Can't resolve 'react-hook-form-resolvers'

I saw similar issue but don't find any solution.

My package.json -

resolver-error

Thanks for your help.

Module not found: Can't resolve 'react-hook-form-resolvers'

Then following the instruction in https://github.com/react-hook-form/react-hook-form-resolvers/blob/master/README.md

Install the module using npm install react-hook-form-resolvers.

Then import yupResolver.

import { yupResolver } from 'react-hook-form-resolvers';

I am getting
Module not found: Can't resolve 'react-hook-form-resolvers' in '{__PATH_TO_A_REMOVED_COMPONENT__}'

When I look into the node_modules/react-hook-form-resolvers it's empty.
Screenshot 2020-05-12 at 06 46 33

Yup context issues & How to reload the form with his new context

Hi,
Issues that i found are :

  • When you place a context props to the yup resolver like {context: {test: "test"}} validation trigger no more, specially for the case of abortEarly which have to be set to false to make it rework properly.
    I expect the form to work even if abortEarly is not set.
  • How can i trigger the new validation form if the context has change ?
    You can follow this example -> https://codesandbox.io/s/magical-almeida-j941j?file=/src/App.js
    User can change his language. If language is 'fr-FR' the test number must less than 2. If language is "en-US" the number must be less than 4.
    You can find those logics in the yup schema.
    Every times the user change the language i call the trigger method to revalidate the form. Now please follow those steps:
  • Start typing "6" to the input and you will get an error. The language is set to 'en-US' and must be less than 4. So type 4. The error disappear.
  • Now switch to the language "fr-FR". Nothing happen ( mode is onChange, reValidateMode is onChange ).
    I expect to get an error message to be test must be less than or equal to 2.
  • Now click on Submit. It's working !
  • Now reduce the number ( with the bottom arrow ) to switch from 4 to 3. The message disappear.
    I expect to have the same error message.
  • Resubmit and you get your message back.

So i think that you have maybe a sort of cache behind the form for the context that keep in memory the first form state. And if you check the log, the lang switch from "fr-FR" to "en-US" every time you submitted or you typed. So you have to different version of this value in your form. One from the form initialisation, One when you submitted the form.
@bluebill1049 can you help me ?

Attempted import error: 'appendErrors' is not exported from 'react-hook-form'.

Have the issue:

./node_modules/@hookform/resolvers/dist/index.esm.js
Attempted import error: 'appendErrors' is not exported from 'react-hook-form'.

My implementation is pretty simple, but when I want just to import:

import { yupResolver } from '@hookform/resolvers';

I see the error above. Even if I comment everything in the component.

Any clue?

Doco: Custom Resolver not respecting validation order

So i'll be brief in case this is expected behavior, referring to the example at:

https://react-hook-form.com/advanced-usage#CustomHookwithResolver

The reducer function doesn't respect the default order of validation as it does by a normal validation schema.

The code fix can simply be:

errors: errors.inner.reduce((allErrors: ObjectMap<string>, currentError: ObjectMap<string>) => {
    return !!allErrors[currentError.path] ? allErrors : {
        ...allErrors,
	[currentError.path]: {
		type: currentError.type ?? 'validation',
		message: currentError.message,
	},
    };
}, {}),

Using .test with Yup causes erroneous validation

I have the following (simplified for this issue) schema:

export const schema = yup
    .object()
    .shape({
        useTimePerTurn: yup.boolean(),
        useTimePerGame: yup.boolean(),
    })
    .test('either-timers', 'You must use at least one timer type.', (value) => {
        const { useTimePerTurn, useTimePerGame } = value
        return useTimePerGame || useTimePerTurn
    })

With this schema, validation of a form won't work, the form will always be considered valid. I could isolate the issue to this line: https://github.com/react-hook-form/resolvers/blob/master/src/yup.ts#L11. I'm new to both Yup and react-hook-form, but my understanding is that a validation error from a test in yup will not have a path, hence the parseErrorSchema() method will return an empty object, breaking the rest of the form validation process.

I threw together a small code sandbox to demonstrate the issue: https://codesandbox.io/s/elegant-brattain-3jp5j?file=/src/App.tsx

And here's a screenshot of the validation error from Yup, notice how path is empty since the error was due to a test failing rather than validation constraints:
image

Failing to build

In my project, and even with the very basic typescript boilerplate (i.e. https://github.com/jsynowiec/node-typescript-boilerplate), including @hookform/resolvers into the project breaks the build.

> [email protected] build /code/nodejs/node-typescript-boilerplate
> tsc -p tsconfig.release.json

node_modules/@hookform/resolvers/dist/joi.d.ts:2:17 - error TS2307: Cannot find module '@hapi/joi' or its corresponding type declarations.

2 import Joi from '@hapi/joi';
                  ~~~~~~~~~~~

node_modules/@hookform/resolvers/dist/superstruct.d.ts:2:25 - error TS2307: Cannot find module 'superstruct' or its corresponding type declarations.

2 import Superstruct from 'superstruct';
                          ~~~~~~~~~~~~~

node_modules/@hookform/resolvers/dist/yup.d.ts:2:17 - error TS2307: Cannot find module 'yup' or its corresponding type declarations.

2 import Yup from 'yup';

Question: How to dynamically add new Yup validation rule?

I'm currently using Yup to validate my form. However, I have a few inputs that is dynamically generated and the input name is also generated on runtime. Is there a way for me to add new validation rule via register or any other means? Thanks

IE11 Support

This package does not work with IE11. The react-hook-form latest release looks like they're making efforts to support IE11 until it's unsupported, are we able to release a transpiled version of this package as well?

Add additional properties to Zod resolver for i18n

Currently, there is only message and type (= code) shown from each error that may occur, but for each error code there are additional fields (https://github.com/vriad/zod/blob/master/ERROR_HANDLING.md#zoderrorcode), which are getting filtered:

resolvers/src/zod.ts

Lines 20 to 21 in 36f7816

return zodError.errors.reduce<Record<string, any>>(
(previous, { path, message, code: type }) => {

If you want to add i18n to your project and use the message provided from the resolver, it is e.g. not possible to include the data types (without doing nasty things like substring() or similar).

Example

For an invalid_type error, the resolvers output is something like this

{
    message: 'Expected date, received string',
    type: 'invalid_type'
 }

but Zod is already able to generate

{
    code: 'invalid_type',
    expected: 'date',
    received: 'string',
    path: [Array],
    message: 'Expected date, received string' 
}

which would make i18n possible due to the expected and received fields.

Is there a reason why these additional fields are filtered?

Type problems after update resolver to 1.3.0

After update @hookform/resolvers to the version 1.3.0, this code above no longer works.

The TS compiler points out the error:

Type 'Resolver<AssertsShape<Assign<Record<string, AnySchema<any, any, any> | Reference<unknown> | Lazy<any, any>>, { title: RequiredStringSchema<string, Record<string, any>>; buttonTitle: RequiredStringSchema<...>; exibitionMode: RequiredStringSchema<...>; link: RequiredStringSchema<...>; duration: NumberSchema<...>; }>>,...' is not assignable to type 'Resolver<FormData, object>'.
  Types of parameters 'values' and 'values' are incompatible.
    Type 'FormData' is not assignable to type '{ [x: string]: never; title: string; buttonTitle: string; exibitionMode: string; link: string; duration: number; }'.
      Index signature is missing in type 'FormData'.ts(2322)
form.d.ts(39, 5): The expected type comes from property 'resolver' which is declared here on type 'Partial<{ mode: "onBlur" | "onChange" | "onSubmit" | "onTouched"

If I comment the lines of exibitionMode and colorBackground the error disappears.

This is the code that I'm working with

import { useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
import { object, string, number } from 'yup'

enum Color {
  DARK = 'dark',
  LIGHT = 'light',
  PURPLE = 'purple',
  ORANGE = 'orange',
  RED = 'red',
  GREEN = 'green'
}

enum ExibitionMode {
  INFINITY = 'infinity',
  LIMITED = 'limited'
}

interface FormData {
  title: string,
  buttonTitle: string,
  exibitionMode: ExibitionMode,
  link: string,
  duration: number,
  colorBackground: Color
}

const TITLE_MAX_LENGTH = 96
const BUTTON_TITLE_MAX_LENGTH = 28

const schema = object().shape({
  title: string().max(TITLE_MAX_LENGTH).required(),
  buttonTitle: string().max(BUTTON_TITLE_MAX_LENGTH).required(),
  exibitionMode: string().required(),
  link: string().required().url(),
  duration: number().when('exibitionMode', (exibitionMode, schema) => {
    return exibitionMode === ExibitionMode.LIMITED ? schema.min(1).required() : schema
  })
})

const Test = () => {
  const { register, handleSubmit } = useForm<FormData>({
    resolver: yupResolver(schema),
    mode: 'onBlur'
  })
}

Zod resolver: numbers, dates

Zod resolver refuses to accept valid input[type=number] and input[type=date]

import React from "react";
import { useForm } from "react-hook-form";
import * as z from 'zod';
import { zodResolver } from "@hookform/resolvers/zod";

const schema = z.object({
  num: z.number(),
  date: z.date(),
})

export default function Foo(): JSX.Element {
  const { register, handleSubmit, errors } = useForm({ resolver: zodResolver(schema) })

  const onSubmit = handleSubmit((values) => {
    console.log(values)
  })

  const numErr = errors.num?.message
  const dateErr = errors.date?.message

  return (
    <form onSubmit={onSubmit}>
      <input name="num" type="number" inputMode="decimal" ref={register} />

      {numErr && <p style={{ color: "red" }}>{numErr}</p>}

      <input name="date" type="date" ref={register} />

      {dateErr && <p style={{ color: "red" }}>{dateErr}</p>}

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

while Yup resolver works perfectly

Might try to fix this myself when I find time

bug ie11 export not working in 1.1.0

After upgrade to @hookform/resolvers, the ie11 export seems broken.

The import was working on prior version with:

Code

import { yupResolver } from '@hookform/resolvers/dist/ie11/yup';

Now gives a

ModuleNotFoundError: Module not found: Error: Can't resolve '@hookform/resolvers/dist/ie11/yup'

Environement

NextJs 9.5.2, typescript 4.1.1, latest react-hook-form / resolver

Content of the node_modules

image

yupResolver loses errors when combining nested errors

Problem

The yupResolver loses some nested errors

Background

I have a schema for validating dates. The input format is an object {day, month, year}. This is because my input form has three separate fields.

The intention is that when the error is due to a specific field, I can highlight that field in the UI. There are some validation conditions that apply to the whole date, and for those I will highlight all three fields.

Details

The schema (simplified slightly):

yup
    .object({
      day: yup
        .number()
        .max(31, "Day of birth must be in range 1-31"),
      month: yup
        .number()
        .max(12, "Month of birth must be in range 1-12"),
      year: yup
        .number()
        .required("Year of birth is required")
    })
  .test({
    name: "is-valid-date",
    message: "Please enter a valid date.",
    test: value => moment(value).isValid(),
  })

When the input value fails validation on both a specific field, and on the whole value, the errors object that I receive back contains only the outer error.

i.e. for value {day: 1, month:999, year: 1993 }, the resulting error from yup includes both "Month of birth must be in range 1-12" and "Please enter a valid date."
but the errors object returned by yupResolver only contains "Please enter a valid date."

Root cause?

I think this is due to the order of the keys in the object that yup returns, and a bug in https://github.com/react-hook-form/react-hook-form/blob/V6/src/logic/transformToNestObject.test.ts.
This transform tool has unexpected behaviour depending on the order of the input.

I have demonstrated this in a PR:
react-hook-form/react-hook-form#1722
The first test passes. The second loses information. The only difference is the ordering of keys in the input.

I am not sure if the fix should be in transformToNestObject, because that may have other dependencies.

Yup resolver failing to validate one field dependent on another

Hi there! First of all I'm not sure if this problem is caused by the resolver, if it's a problem with Yup itself or simply because I don't have a proper understanding of the usage of this two wonderful tools.

So I'm trying to validate a field based on the value of another field (comparing that last date is greater than first date). But the error messages have been rather inconsistent in this case, usually not disappearing when it should. I made a sandbox to reproduce the issue in a simplified way (two numbers, first one should be less than the second one).

Working sandbox: https://codesandbox.io/s/polished-framework-ofvx8

Steps to reproduce:

  1. Insert a number in the first input
  2. Insert a lower number in the second input (you should get an error message)
  3. Change the first input so that first < second
  4. Blur

Desired outcome:
After step 3, the error message on the second input should disappear.

Current outcome:
The error message on the second input remains even though it went through the validation (as showcased in the console). Also note that even if the error message doesn't disappear, the "submit" is now clickable as the form is valid (disabled is form invalid).

yupresolver doesnt fire all validation at once.

The yup validation is not firing all validation at one go on the 'fullName' field.

import { useForm, Controller } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers";
import { TextField } from "@material-ui/core";
import "./styles.css";

const schema = yup.object().shape({
  name: yup
    .string()
    .min(3)
    .lowercase()
    .email()
    .required()
});

export default function App() {
  const { handleSubmit, control, errors } = useForm({
    resolver: yupResolver(schema)
  });
  const onSubmit = data => {
    console.log(data);
  };
  console.log(`on render errors: ${JSON.stringify(errors, null, 4)}`);
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        as={<TextField />}
        name="name"
        control={control}
        defaultValue=""
      />
      <button>Submit</button>
    </form>
  );
}

Here's CSB: https://codesandbox.io/s/competent-greider-8c8w8

Expected result: I was expecting multiple validation erros on name field.
Actual result: In contrast I can only get one validaiton error at a time.
image

I take abortEarly : false by default.

Any idea?

TSC: Cannot find module '@hapi/joi'

There's an issue where the joi resolver is importing from @hapi/joi but @hapi/joi is a devDependency.

I'm thinking @hapi/joi needs to be moved to dependencies?

../../node_modules/@hookform/resolvers/dist/joi.d.ts:2:17 - error TS2307: Cannot find module '@hapi/joi' or its corresponding type declarations.

Cannot pass a component to yupResolver schema error messages

Describe the bug
When passing a component as an error message. I get an error Maximum callstack size exceeded (more info about an error in codesandbox link below).

yupResolver(
      yup.object().shape({
        email: yup
          .string()
          .required(<span>Required</span>)
          .test(
            "matches",
            "Wrong email",
            (value) => value === "[email protected]"
          )
      })
    ),

Codesandbox link
https://codesandbox.io/s/silly-thunder-4y5dj?file=/src/App.js:294-561

Additional context
In the project, we have our own Translation components, which we would like to pass as an error message.

IE11 crashing with v0.1.0 and react-hook-form v6.08

It reports syntax error on this line:

const parseErrorSchema = (error, validateAllFieldCriteria) => ...

which is the code of the resolvers. I assume this needs some transpiling since IE doesn't know about const keyword?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.