简体   繁体   中英

Listen to 'invalid' event on a React component

I have a React input component and I'd like to use HTML5 Constraint Validation to validate user input after each blur.

var TextField = React.createClass({

    handleValidation: function () {
        React.findDOMNode(this.refs.textField).checkValidity();
        //TODO listen on invalid event
    },

    render: function () {
        return (
            <input ref="textField" onBlur={this.handleValidation} />
        )
    }
});

You could try putting an event listener in the componentDidMount function... maybe something like this?

componentDidMount: function() {
  React.findDOMNode(this.refs.textField).addEventListener("invalid", function () {
    //do something here
  });
},

Just keep in mind if you navigate to another component you should remove the event listeners first. Hope this helps.

Is there a reason for listening to this event?

"checkValidity() method, which returns false if the element fails to satisfy any of its constraints, or true otherwise." MDN source

So you can just check if this function returns false.

if (!React.findDOMNode(this.refs.textField).checkValidity()) {
  // not valid
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM