samedi 24 avril 2021

Validate input when the user stops typing - ReactJs

I want to perform an input validation only when the user stops typing.

<SmallInput
   onChange={() => {
        if (unitsPerUser < this.state._unitsPerUser) {
                unitsPerUserError = true;
                this._updateUnitsPerUser("");
                this.setState({
                      unitsPerUser: "",
                      unitsPerUserError,
                      unitsPerUserErrorMsg: `Per user units cannot be less than ${this.state._unitsPerUser}`,
                });
        }
   }}
/>

I want to perform this validation not on keyup or keydown but when the user is done typing.

How can I use any tool (like debounce for example) to achieve this? Thanks in advance.

EDIT - I tried this, but it doesn't seem to work -

<SmallInput
   onChange={() => {
        if (unitsPerUser < this.state._unitsPerUser) {
                let typingTimer;
                clearTimeout(typingTimer);
                setTimeout(() => {
                     unitsPerUserError = true;
                     this._updateUnitsPerUser("");
                     this.setState({
                             unitsPerUser: "",
                             unitsPerUserError,
                             unitsPerUserErrorMsg: `Per user units cannot be less than ${this.state._unitsPerUser}`,
                     });
                 }, 1000);
        }
   }}
/>



Aucun commentaire:

Enregistrer un commentaire