Home > Enterprise >  oninvalid attribute not rendering in React js
oninvalid attribute not rendering in React js

Time:10-20

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.

CodePudding user response:

The attribute names should onInvalid instead of oninvalid and onInput instead of oninput. Additionally, you need to call the setCustomValidity function on the input field as follow (because the input field is the target of the event):

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

CodePudding user response:

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>
  );
}
  • Related