I have a form in a React function component and I want to change the styles(color, background color) for the error messages that appear when the required attribute is set to true for a field.
I have a const formRef = React.useRef(); and I use it to check if I can go further like this:
if (formRef.current.reportValidity()) {
// do stuff
}
Any suggestions?
As far as I know, you can not style this default validation error from html. What I did so far was to disable native validation, and listen to input's change, and in case of error update some state. For example
const [inputValue, setInputValue] = useState<string>('');
const [errorMessage, setErrorMessage] = useState<string>(''):
const MIN_LENGTH = 5;
/* update input value */
const handleInputChange = (event) => {
const value = event.target.value;
/* clear error on change */
if (errorMessage !== '') {
setErrorMessage('');
}
}
/* set error if needed on blur */
const handleInputBlur = () => {
if (inputValue.length <= MIN_LENGTH) {
setErrorMessage(`Username should have at least ${MIN_LENGTH} characters`
}
}
return (
<div>
<input onChange={handleInputChange} onBlur={handleInputBlur}
value={inputValue} />
{errorMessage !== '' && <p>{errorMessage}</p>
</div>
)