Last active
February 2, 2022 05:33
-
-
Save KolbySisk/2d70180da97fa0c062db998934e0de86 to your computer and use it in GitHub Desktop.
Slightly Complex Form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from "react"; | |
export default function SlightlyComplexForm() { | |
const [urlVisible, setUrlVisible] = useState(false); | |
const handleSubmit = async (event) => { | |
// Same as before | |
}; | |
const handleEmailChange = (event) => { | |
setUrlVisible(Boolean(event.target.value.length)); | |
}; | |
const handlePasswordBlur = (event) => { | |
event.target.reportValidity() | |
} | |
return ( | |
<form onSubmit={handleSubmit}> | |
<input name="email" type="email" required onChange={handleEmailChange} /> | |
<input name="password" type="password" minlength="6" onBlur={handlePasswordBlur} required /> | |
{urlVisible && <input name="url" type="url" required />} | |
<button>Submit</button> | |
</form> | |
); | |
} |
You could use checkValidity
. reportValidity
will trigger validation as if the form was submitted - showing the native error message. checkValidity
will not trigger error messages to appear. If you're rolling your own error messages then go with checkValidity
and toggle some state to show the message 👍
I see! Thanks a lot for explaining that. I've never used this api, so I'm definitely going to play around with this now, cheers! :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Correct me if I'm wrong, but shouldn't we use
checkValidity
on password blur instead ofreportValidity
?Btw, great article, thank you! 🙏