Javascript mask is breaking if I type the date quickly

Asked

Viewed 52 times

0

I am trying to make a javascript data mask to use in the dd/mm/yyyy format React for a custom date selection component.

If I press the keys slowly, the mask correctly applies the format, but if I press the numbers quickly, the mask is broken, not adding the '/'

My component:

<DateInput
       name="date"
       placeholder="Data"
       value={this.props.data}
       dateFormat="DD/MM/YYYY"
       onChange={this.props.changeDataTarefa}
       animation="none"
       onKeyUp={() => this.props.changeDataTarefaMask(this.fixDatePattern(this.props.data))}/>

My duties:

 fixDatePattern(currDate) {
        var currentDate = currDate;
        if (currentDate){
            var currentLength = currentDate.length;
            var lastNumberEntered = currentDate[currentLength - 1];
        }

        if (!this.isNumber(lastNumberEntered) && currentDate) {
          return currentDate.substring(0, currentLength - 1);
        }

        if (currentLength > 10) {
          return currentDate.substring(0, 10);
        }
        let dateCountTracker = 0

        if (currentLength == 1 && currentDate > 1) {
          var transformedDate = "0" + currentDate + '/';
          dateCountTracker = 2;
          currentLength = transformedDate.length;
          return transformedDate;
        } else if (currentLength == 4 && currentDate[3] > 3) {
          let transformedDate = currentDate.substring(0, 3) + "0" + currentDate[3] + '/';
          dateCountTracker = 5;
          currentLength = transformedDate.length;
          return transformedDate;
        } else if (currentLength == 2 && (dateCountTracker != 2 && dateCountTracker != 3)) {
          dateCountTracker = currentLength;
          return currentDate + '/';
        } else if (currentLength == 5 && (dateCountTracker != 5 && dateCountTracker != 6)) {
          dateCountTracker = currentLength;
          return currentDate + '/';
        }

        dateCountTracker = currentLength;
        return currentDate;
      }

    isNumber(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
      }

Why does this happen?

  • Hi Veronese, could the function changeDataTarefa? it seems to me that a problem is occurring when setting the state. Your function of checking the typed date could be before calling changeDataTarefa. Let me see how you are and answer you better.

1 answer

0

I believe you should wear onKeyPress instead of onKeyUp:

<DateInput
       name="date"
       placeholder="Data"
       value={this.props.data}
       dateFormat="DD/MM/YYYY"
       onChange={this.props.changeDataTarefa}
       animation="none"
       onKeyPress={() => this.props.changeDataTarefaMask(this.fixDatePattern(this.props.data))}/>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.