Giter Club home page Giter Club logo

Comments (4)

f10l avatar f10l commented on May 29, 2024 1

+1, I needed this functionality yesterday and my quick hack was to blur and focus the input to trigger the validation. Would love to see a built-in solution.

from react-use-form-state.

timiscoding avatar timiscoding commented on May 29, 2024 1

I spent way too much time trying to figure out how the form submit event could be stopped even if some fields were unvisited and invalid. So inspired by the discussion here, hopefully someone finds my solution useful. The trick was decoupling the submit event (for button clicks) from the onSubmit callback and firing the event manually. What I ended up doing was exposing a submit method in a custom hook that

  • iterates through the input elements, firing the blur event to trigger validation.
  • set a boolean state variable true (I called it submitRequest). This is needed as we can't read the validity yet.
  • on the next render, we use an effect hook to check 2 things:
    1. all fields are valid
    2. the submitRequest is set to true.

Provided those criteria are met, we dispatch a submit event for the onSubmit handler as normal. The submitRequest flag is reset to false to prevent multiple renders from firing the submit more than once.

See Code sandbox

from react-use-form-state.

wsmd avatar wsmd commented on May 29, 2024

Hi @EmilEriksen - Thanks for the issue and sorry for the delay.

Unfortunately, this isn't possible with where the library stands today. Currently, validation needs access to the DOM element which can only be possible using the change and blur events, both of which are fired upon user interaction.

That said, you might be able to achieve something similar by creating a custom validator that can validate inputs dependently from useFormState. Then you can merge the validity of the latter by the custom validation object that you created to get the final result.

Here's an example that validate the input using the HTML5 constraint validation:

/**
 * This custom hook will validate inputs by accessing the underlying DOM node
 * directly using refs
 */
function useFormValidator() {
  const [validity, setValidity] = React.useState({});
  const inputRefs = useRef({});
  const bind = useCallback(input => {
    if (input) {
      inputRefs.current[input.name] = input;
    }
  }, []);
  const validate = () => {
    for (const name in inputRefs.current) {
      setValidity(validityState => ({
        ...validityState,
        [name]: inputRefs.current[name].validity.valid
      }));
    }
  };
  return { bind, validate, validity };
}

function App() {
  const [formState, input] = useFormState();
  const validator = useFormValidator();

  // final validation result
  const validity = { ...validator.validity, ...formState.validity };

  return (
    <>
      <input {...input.text("username")} ref={validator.bind} required />
      <button onClick={validator.validate}>Click me to validate</button>
    </>
  );
}

Here's a working example: https://codesandbox.io/s/0y87pzxv3w

This isn't perfect, of course, and it might not cover all cases but hopefully it can give you an idea that you can expand on. Supporting something like that will cause breaking changes, but it's definitely something I'll keep in mind for future major releases of react-use-form-state.


Note to self: duplicate of #57 #47

from react-use-form-state.

jwalton avatar jwalton commented on May 29, 2024

validation needs access to the DOM element which can only be possible using the change and blur events

Well... you could pass a ref to every <input>, and then you could get access to them whenever you wanted to. You'd have to do a little bit of cleverness if you want to let someone else also pass a ref to the input, but I can think of a couple of ways it could be done.

from react-use-form-state.

Related Issues (20)

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.