A snippet of code that uses the element.validity.valid and element.validationMessage properties.
Full code:
const [error, setError] = useState("")
function onBlur(event) {
if (event.target.validity.valid) {
setError("")
} else {
setError(event.target.validationMessage)
}
}
<div>
<input minLength={3} onBlur={onBlur} />
<div>{error}</div>
</div>
A screenshot of a page shows an input filled with a single character and a styled error message stating, "Please lengthen this text to 3 characters or more (you are currently using 1 character)."
Did you know you can use the built-in browser validation API with JavaScript to control the rendering of error messages?
Along with its simplicity, you also get internationalization for free ✨