How to allow only numbers in textbox in reactjs?

后端 未结 7 545
感情败类
感情败类 2020-12-03 05:03

How to allow only numbers in textbox in reactjs using regular expression only?

7条回答
  •  北海茫月
    2020-12-03 05:35

    Even though you said regular expression only this is high up in Google without specifying regular expression (as that's not stated in the title) so I thought I'd add another simple way, not using regular expressions. And given the test results linked below it'd seem silly to use regular expressions for simple use cases.

    I found this on another post that I can no longer find. I believe it was referred to as the self-equals check... Not entirely sure how it works. But it's at least 20 times faster than Regex in Chrome (from the test results).

    isNumeric(number) {
      if (+number === +number) { // if is a number
          return true;
      }
    
      return false;
    }
    

    Benchmarking self-equals vs regex vs NaN

    There are revisions to this test at the bottom of the page, number 5 is the one that corresponds to the post I found that had this simple solution, I'm unsure how the other revisions differ.

    I use it for my positive number only textboxes like this:

    isValidQuantityInput() {
      const value = +this.state.quantityInputText; // convert to number
      if (value !== +value || value < 0) { // if fails validity check
        return false;
      }
    
      return true;
    }
    

    I don't bind the value of the input to the data as that causes weird usability issues such as not being able to clear the field without highlighting etc... quantityInputText holds the input text, then I validate it and if it is valid I set my data to it's value.

提交回复
热议问题