wsmd / react-use-form-state

📄 React hook for managing forms and inputs state

Home Page:http://react-use-form-state.now.sh

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: Custom validate method

hshelbur opened this issue · comments

I am returning an error in a validation function, however the form will still submit and the error is not displayed similarly to the 'Please fill out this field.' error message for required fields or the minimum length generated error message.

Is the current functionality that I must just check for any errors in my handleSubmit function and display these errors on my own, or am I not implementing this correctly? Simple code example:

<TextInput 
              required 
              minLength="6" 
              {...password({
                name: `newPassword`,
                validate: (value) => {
                  const containsOnlyLetters = /(?=.*[^a-zA-Z])/
                  if (!containsOnlyLetters.test(value)) {
                    return 'Password must contain a non-letter character'
                  }
                }
              })} 
              labelText="New Password" 
            />

Great library by the way, thanks!

Hi @hshelbur,

Is the current functionality that I must just check for any errors in my handleSubmit function and display these errors on my own

That's one way to do it! This library is only concerned with managing form state giving you the freedom to build and render your own forms however you want (including rendering custom errors).

however the form will still submit and the error is not displayed similarly to the 'Please fill out this field.' error message for required fields or the minimum length generated error message.

The errors you're describing here are implemented and displayed natively via the browser (by using the required and minlength attributes), not via this library.

That said, you could still totally set custom errors via this library, but you'd have to use the native validation API, so I understand that it may not be very intuitive at first.

Screen Shot 2019-10-16 at 8 15 31 PM

The 3rd argument of the validate method is the change event which gives you access to the underlying DOM node. You can use this to call setCustomValidity with the custom error message.

Here's an example to demonstrate how this could be implemented:

https://codesandbox.io/s/setcustomvalidity-v2ue3

I hope this helps!