Comments (4)
+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.
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:
- all fields are valid
- 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.
from react-use-form-state.
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.
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)
- Nested objects support HOT 1
- validate that fields match HOT 1
- Async validation HOT 2
- setField should not be packaged with formState HOT 2
- Published version of types lacking pristine/isPristine? HOT 2
- BUG: `validate` function is called on blur when `validateOnBlur` is not specified/false HOT 2
- react update - Cannot update a component from inside the function body of a different component. HOT 10
- Auto-saving forms HOT 1
- Reference Nested Values with Name HOT 1
- Question: how would one handle "dynamically added fields" ? HOT 2
- isPristine feature is not present in dist package HOT 5
- Password confirmation use case questions HOT 2
- Raw inputs are not given a `name` prop HOT 1
- Question - trigger validation on submit HOT 1
- Request: reset current values to initial values HOT 1
- Function to reset pristine HOT 2
- Request: Input type "number" with BaseInputProps - value is "number" type
- Maintained? HOT 4
- Unable to install with react's latest version react ^17.0.2 HOT 1
- React warning: Cannot update a component while rendering a different component when using `...text` in child component
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-use-form-state.