Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

223
Views
can't modify style of default error messages in forms in React

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
    }

enter image description here

Any suggestions?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!