What's the best way to automatically insert slashes '/' in date fields

后端 未结 12 1481
执念已碎
执念已碎 2020-12-06 04:55

I\'m trying to add functionality to input date fields so as when the users enters in digits, slashes \"/\" get automatically added.

So suppose I have the following

12条回答
  •  有刺的猬
    2020-12-06 05:18

    My regex solution for React:

    // add auto "/" for date, i.e. MM/YY
      handleExpInput(e) {
    
        // ignore invalid input
        if (!/^\d{0,2}\/?\d{0,2}$/.test(e.target.value)) {
          return;
        }
    
        let input = e.target.value;
    
        if (/^\d{3,}$/.test(input)) {
          input = input.match(new RegExp('.{1,2}', 'g')).join('/');
        }
    
        this.setState({
          expDateShow: input,
        });
      }
    

提交回复
热议问题