'oninvalid attribute not rendering in React js

I am trying to add oninvalid attribute in HTML element under React js code. (using react hooks not class based)

 const openEndedAnswer = answer => {
        return (<>
            <input type="text" className="form-control"
                required="required"
                oninvalid="this.setCustomValidity('Enter User Name Here')"
                oninput="this.setCustomValidity('')"
                maxLength="255"
                id={`answer_${question.id}`}
                name={`answer_${question.id}`}
                onChange={e => updatePostForm(e)}
                pattern=".*[^ ].*"
                title=" No white spaces"
            />
        </>)
    }

But it never renders in the browser. all other attributes can be seen in F12 source view.



Solution 1:[1]

Try onInvalid instead:

export default function App() {
  return (
    <form>
      Name:{" "}
      <input
        type="text"
        onInvalid={() => console.log("working!")}
        name="fname"
        required
      />
      <input type="submit" value="Submit" />
    </form>
  );
}

Solution 2:[2]

If you are using React with javascript this should work:

onInvalid={e => e.target.setCustomValidity('Your custom message')}
onInput={e => e.target.setCustomValidity('')}

But if you are working with React with typescript you also need to add this:

onInvalid={e => (e.target as HTMLInputElement).setCustomValidity('Enter User Name Here')}
onInput={e => (e.target as HTMLInputElement).setCustomValidity('')}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Erik
Solution 2 Wings