Skip to content

Instantly share code, notes, and snippets.

@KolbySisk
Last active February 2, 2022 05:33
Show Gist options
  • Save KolbySisk/2d70180da97fa0c062db998934e0de86 to your computer and use it in GitHub Desktop.
Save KolbySisk/2d70180da97fa0c062db998934e0de86 to your computer and use it in GitHub Desktop.
Slightly Complex Form
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>
);
}
@KolbySisk
Copy link
Author

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 👍

@sitek94
Copy link

sitek94 commented Feb 2, 2022

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