question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Input required and validation

See original GitHub issue

Creating this as a round up of existing open validation issues as of now. Hoping to create some kind of proposed solution and seeking feedback before creating a PR though others are welcome to try as well so long as we all know the challenges and impact of solving for this.

Use-case:

As a developer working within in a form, I would like to apply native html validation to my react-select component.

Duplicates:

#2751 - Required attribute should be passed down… #3625 - Using Required attribute #1453 - Add validation support #4416 - Obtaining focus from the hidden input inside react-select #3140 - How to make react-select required in a form? #4450 - How to make reactselect get focus when required and empty

Challenges

1. Single Input

  • Currently default behavior of react-select is to clear inputValue onChange event so validation on this input would by default always be missing a value, so applied validation to this input is already not-out-of-the-box easy to implement

Possible proposal: Introduce a visibly hidden text input which renders the selected value

2. Multi Input

  • What kind of validation rules should be applied? How would this be implemented?

Possible proposal: Introduce a visibly hidden text/select input which concatenates all of the values together and apply a multiple attribute

3. isSearchable=false

  • Currently a DummyInput is used for focusing the content to replicate the focus and blur functionality currently built-in

Possible proposal: Introduce a visibly hidden select input. Apply multiple attribute if it is a Multi Input.

4. Visibly hidden input

Notes: This visually hidden element cannot be readonly, disabled, have style display: none, and would likely have tabindex="-1" to ensure it does not interfere with focus order.

Also currently (and curiously), the name prop is passed to a generated “FormField”. My proposition would be to rewrite this formally as a component which also serves the benefit of decomposing Select.js.

5. Styling since anything other than a single searchable Select requires a visibly hidden input (type text or select or anything else a user suggests), then how would styling this element be possible?

Possible proposal:

  • Assuming above proposals, identify new/existing component to be used for validity
  • On mount of validator component, call element.addEventListener('invalid', handleInvalid)
  • Allow method handleInvalid to set new internal state isInvalid
  • Add internal state variable isValid and expose to other components (to style borders, colors, icons, etc)
  • Create new style component which would apply styles directly to the invalid element
  • Apply BEM modifier --is-invalid to this element to be specified in CSS (though :invalid is always available to the user as well)
  • On unmount of validator component, call element.removeEventListener('invalid', handleInvalid)

6. Breaking changes

Would changing the behavior of the FormField be a breaking change? I suppose it is very possible depending on test suites and formalizing this as a component could have other impacts.

Most everything seems additive especially since adding validation would likely be additive, however, due to the nature of this application, there exists the possibility that either required or isRequired could both already be pre-existing props so it is possible

There is slight possibility of introducing conflicting css names. Introducing InvalidInput as a stylable component which is applied as classNamePrefix__invalid-input could help avoid these collisions.

Perhaps greater likelihood is introducing css to apply to containers. It’s possible classNamePrefix__control--is-invalid is already used, but I also believe it should be discouraged from applying internal naming conventions.

Maybe, we consider adding another className to the control styled element called classNamePrefix__validated-control and styles can cascade from classNamePrefix__validated-control--is-invalid to avoid naming conflicts.

That said, any feedback? If the changes are breaking then we would want to target version 4 rather than 3.2, but wanted to get community buy-in to better understand how to solve this issue given the flexibility and current functionality of react-select.

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:11
  • Comments:13

github_iconTop GitHub Comments

31reactions
ebonowcommented, Dec 13, 2020

In some ways I agree and I do love RHF, but in other ways it feels problematic to tell users to adopt an entire form management library or write your own validation wrapper when there is already built-in native support input and select DOM elements.

If react-select is going to position itself as a react based replacement for a select input, it should also support native validation or at least enable its users to do so easily.

21reactions
karimdagharicommented, Dec 13, 2020

As far as I’m concerned, I don’t think that this is much of an issue. I think this should be left for the dev to solve and keep it out of react-select’ scope.

For anyone wondering how I solved this “issue”:

  1. Create a wrapper Select component around react-select
  2. (I’m using RHF for managing forms) add a control and a rules prop (to pass down to react-select)
  3. Technically speaking, that already does the job very well, visually speaking, it’s not there.
  4. Add an error prop to detect errors (again, using RHF here) and apply certain css conditionally

The code in question:

interface CustomSelectProps extends ReactSelectProps, SharedSelectProps {
  native: false;
  control: Control<any>;
  rules: RegisterOptions;
  /**
   * The error object
   */
  error?: unknown;
  /**
   * The associated error message
   */
  errorMessage?: string;
}

// ...

<Controller
      name={name ?? ""}
      control={control}
      rules={rules}
      defaultValue={defaultValue}
      as={
        <ReactSelect
          {...props}
          id={normalizedId}
          instanceId={normalizedId}
          className={cn({
            "rounded-md shadow-md": true,
            "border-gray-200 ": !error,
            "border-red-500": error
          })}
        />
      }
    />
Read more comments on GitHub >

github_iconTop Results From Across the Web

HTML input required Attribute - W3Schools
The required attribute is a boolean attribute. When present, it specifies that an input field must be filled out before submitting the form....
Read more >
Client-side form validation - Learn web development | MDN
The simplest HTML validation feature is the required attribute. To make an input mandatory, add this attribute to the element.
Read more >
How to perform form validation for a required field in HTML
1. Required attribute: If you want to make an input mandatory to be entered by the user, you can use the required attribute....
Read more >
Validating Input | Web Accessibility Initiative (WAI) - W3C
Validating required input ... Forms frequently include required input that needs to be clearly identified using labels. Also, the required attribute can be...
Read more >
HTML Input Validation with JavaScript
When a user attempts to submit an HTML form, their browser first performs client-side validation to check if the form data is valid....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found