GithubHelp home page GithubHelp logo

react-hook-form / error-message Goto Github PK

View Code? Open in Web Editor NEW
340.0 4.0 15.0 1.92 MB

๐Ÿ“‹ Error message component

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

License: MIT License

JavaScript 6.95% TypeScript 92.49% Shell 0.56%
forms react message component error-handling errormessage error-messages

error-message'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].

error-message's People

Contributors

alfiejones avatar azizur avatar bluebill1049 avatar dependabot[bot] avatar ianvs avatar jorisre avatar kotarella1110 avatar phil-scott-78 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

error-message's Issues

How to get error count

As per accessibility requirement we need to show total number of errors in a form.
For example:

  1. A form with First name, Last name, email, age, telephone are required field.
  2. User clicks on submit without entering any value to input fields.
  3. We need to show a message on top of the page as "There are 5 errors". Screen reader will announce this message (helpful for non-sighted user).

I tried error.length and did not work. Want to know how can I achieve this to full fill accessibility requirement.

Doesn't work with a regular form for some reason

So I have something like:

// ...
import { ErrorMessage } from '@hookform/error-message';

function MyComponent() {
  const {
          formState: { errors },
          trigger,
      } = useFormContext();
  
  const acceptChanges = async function () {
          const valid = await trigger();
          if (valid) {
              await submit?.();
          }
      };
  
  console.log({ errors });
  
  return (
    <>
      {/* .... */}
      <Button onClick={acceptChanges}>{t('Save')}</Button>
      <ErrorMessage errors={errors} name="singleErrorInput" render={({ message }) => <p>{message}</p>} />
    </>
  );
}

and upon submitting the form with errors, while errors object gets filled, e.g.:

{
    "deviceGroupId": {
        "message": "ะ“ั€ัƒะฟะฟะฐ ัƒัั‚ั€ะพะนัั‚ะฒ is a required field",
        "type": "required"
    },
    "state": {
        "message": "State is a required field",
        "type": "required"
    }
}

<ErrorMessage> component renders nothing and the render() doesn't get invoked.

[email protected]
@hookform/[email protected]

Object(...) is not a function

Hi all,

First of all, thanks a lot for providing us with a tool like this, it's a really good idea.

However, I can't seem to make it work, for some reason it keeps saying Object(...) is not a function.

I followed the basic example in the doc, here is my code:

https://jsfiddle.net/qa846skp/

(used fiddle just for the colors)

And the error:
error

Props as and render are not compatible

Hi there ๐Ÿ‘‹

I'm upgrading from react-hook-form v5 to v6 following migration guide, and I think that I have found a possible issue with as and render props.

In v5, when render prop was children, if both are present, both was applied (as as wrapper component and children for rendering message. Here is a CodeSandbox (forked from v5 docs) that demostrates that it works like a charm:
Edit react-hook-form-v5-ts-errorMessage

But now, in v6, after moving children to render, it seems that render and as are mutually exclusive. If as prop is present, render prop won't be applied. Here is another CodeSandbox (forked from v6 docs) that should work like in the other but sadly not:
Edit react-hook-form-v6-ts-errorMessage

Is this an expected behaviour or an issue?

Thanks a lot, you are really awesome ๐ŸŽ‰

Styled components and as prop

Hi. First of all thanks for a great library which react-hook-form is.

I tried to use ErrorMessage component in combination with styled-components. For the record I'm using TypeScript. Sadly, both apis - your component and styled method - accept as prop. So when I do

const StyledErrorMessage = styled(ErrorMessage)`
  color: #f76479;
  font-size: 10px;
`;

<StyledErrorMessage errors={errors} name="avatarUrl"  as="span" />

Typescript goes nuts and error is shown

No overload matches this call.
  Overload 1 of 2, '(props: Pick<Pick<Assign<{ as?: "symbol" | "object" | "a" | "abbr" | "address" | "area" | "article" | "aside" | "audio" | "b" | "base" | "bdi" | "bdo" | "big" | "blockquote" | "body" | "br" | "button" | ... 160 more ... | undefined; errors?: DeepMap<...> | undefined; name: string; message?: string | undefined; render?: ((data: { ...; }) => ReactNode) | undefined; }, any>, string | ... 1 more ... | symbol> & Partial<...>, string | ... 1 more ... | symbol> & { ...; } & { ...; }): ReactElement<...>', gave the following error.
    Type 'string' is not assignable to type 'undefined'.
  Overload 2 of 2, '(props: StyledComponentPropsWithAs<"span", any, {}, never>): ReactElement<StyledComponentPropsWithAs<"span", any, {}, never>, string | ... 1 more ... | (new (props: any) => Component<...>)>', gave the following error.
    Type '{ errors: DeepMap<Record<string, any>, FieldError>; name: string; as: "span"; }' is not assignable to type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>, "slot" | ... 253 more ... | "onTransitionEndCapture"> & { ...; }, "slot" | ... 254 more ... | "onTransitionEndCapture"> & Partial<...>, "slot" | ... 254 more ... | "onTransitionEndCapture"> & { ...; } & { ...; }'.
      Property 'errors' does not exist on type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>, "slot" | ... 253 more ... | "onTransitionEndCapture"> & { ...; }, "slot" | ... 254 more ... | "onTransitionEndCapture"> & Partial<...>, "slot" | ... 254 more ... | "onTransitionEndCapture"> & { ...; } & { ...; }'.  TS2769

    52 |             Avatar URL
    53 |             <Input name="avatarUrl" ref={register({ required: 'Avatar URL is required' })} />
  > 54 |             <StyledErrorMessage errors={errors} name="avatarUrl" as="span" />
       |             ^
    55 |           </Label>
    56 |         </FormControl>
    57 |         <FormControl>

I tried to do

const StyledErrorMessage = styled(ErrorMessage).attrs({ as: 'span' })`
  color: #f76479;
  font-size: 10px;
`;

but styled-components treat this as prop as its own. Span is rendered but message is not shown as you might expect because ErrorMessage component is replaced with span tag by styled-components.

To be honest I'm not sure it's really a bug. Just two libraries exposing similar api ๐Ÿ˜„
I thought you should know about as styled-components are pretty popular.

Unable to resolve path to module '@hookform/error-message'

When I update react hook form version from 5.0.3 to 6.0.4, I faced this error
ErrorMessage component not exported from 'react-hook-form'
after installing npm install @hookform/error-message

and edit the imports to
import { ErrorMessage } from '@hookform/error-message';
I faced this error
Unable to resolve path to module '@hookform/error-message'

Maybe not IE11 compatible?

Hello,

I just saw that the package react-hook-form is being imported here. I haven't yet tried out myself but now I'm wondering if this package (error-message) is not IE11 compatible. If so, would it be possible to make it IE11 compatible by using the IE11 version of react-hook-form somehow?

Thanks in advance.

Documentation - "get" method

Hi,

just found in ErrorMessagethere exists a get method for digging into objects especially errors and retrieve nested values, is there any plan to document this in the API docs?

import * as React from 'react';
import { useFormContext, get, FieldErrors } from 'react-hook-form';
import { Props } from './types';

can be used like

 const error = get(errors || methods.formState.errors, name);

This is useful when handling complex nested forms, right now documentation does not expose all the power of react hooks forms utils.
My favorite forms library by far...
Thanks in advance,

NextJS static build throws error unless errors object passed to ErrorMessage

I've been using ErrorMessage with no issues on NextJS client-rendered pages. Based on the documentation, I haven't been passing the errors object to the ErrorMessage component since I'm using a FormProvider.

However, I just tried to use an ErrorMessage in a form on a NextJS statically exported page and it throws an error that says TypeError: Cannot read properties of null (reading 'formState').

After looking through the issues here and reading #52, I tried fetching the errors object inside my component using useFormContext, and passing this to the ErrorMessage. It seems to have resolved the issue.

This workaround works for me, but I wanted to see if this is expected behavior when exporting a static page.

Versions:
NextJS v12.1.0
React-Hook-Form v7.27.1
@hookform/error-message v2.0.0

root.* error support

The component doesn't support new root.* error type, eg name="root.serverError"

Type '"root.serverError"' is not assignable to type FormData

dot syntax names

It appears that

<input name="coordinate.northing" ref={register} />
<ErrorMessage errors={errors} name="coordinate.northing" />

does not function properly. Is this known/expected?

I noticed this test

it('should render correctly with nested errors object', () => {
const { asFragment } = render(
<ErrorMessage
errors={{
nested: {
object: { type: 'object', message: 'object' },
},
}}
name="nested.object"
/>,
);
expect(asFragment()).toMatchSnapshot();
});

But I don't see the same result.

Maybe this is an issue for the main repo since the errors object sent to this component contains

{
 northing: {message: '', type: ''}
}

updating the error message to

<ErrorMessage errors={errors} name="northing" as={ErrorMessageTag} />

does work but that is confusing and can lead to non-unique keys.

update

I messed up. the errors object is coming from my yup resolver schema so once I linked everything up it does work as expected.

error message doesn't seems to work in usefieldarray

the error dont appear in error message
not sure if this is an issue but cant figure out an other way

const { fields } = useFieldArray({
    name: nameForm,
    ...methods.control
  });

fields.map((field: FieldValues, index: number) => {
            const id = '${nameForm}.${index}.checkbox'

            return (
                <input
                  {...methods.register(id, { required: required })}
                />
              </div>
            );
          })

<ErrorMessage
        errors={errors}
        name={nameForm}
        render={({ message }) => {
          return <div className="text-red-500 text-sm">{message}</div>
        }}
      />

Capture dโ€™eฬcran 2022-02-09 aฬ€ 10 29 43

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.