Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 646
Amit Shah Avatar asked Jul 12 '26 23:07

Amit Shah


2 Answers

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('')}
like image 154
Houssam Avatar answered Jul 14 '26 13:07

Houssam


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('')}
like image 42
Wings Avatar answered Jul 14 '26 13:07

Wings