最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - format DDMMYYYY input react as user types - Stack Overflow

programmeradmin6浏览0评论

I have an input box in a React ponent. This is to take a date of birth. I want to add / after each relevant section. i.e. 30/03/2017

Something similar to this but for date of birth as opposed to credit card number.

The user should enter 30 and then it should automatically add the /. This works with my current code, however, it enters a slash after each 2 digits, however, for the year it adds the slash also after each second digit.

See plete React ponent below

class DateInput extends Component {

  constructor(props) {

    this.handleChange = this.handleChange.bind(this);

    this.state = {
      value: ''
    }

  }

  handleChange(val) {

    val = val.split('/').join('');
    val = val.match(new RegExp('.{1,2}', 'g')).join("/");

    this.setState({
        value: val
    });

  }


  render() {

    const {value} = this.state;
    const placeholder = 'DAY/MONTH/YEAR';

    return ( <input type = "text" value={value} placeholder={placeholder}
      onChange = {this.handleChange}/>
    );

  }

}

I have an input box in a React ponent. This is to take a date of birth. I want to add / after each relevant section. i.e. 30/03/2017

Something similar to this but for date of birth as opposed to credit card number.

The user should enter 30 and then it should automatically add the /. This works with my current code, however, it enters a slash after each 2 digits, however, for the year it adds the slash also after each second digit.

See plete React ponent below

class DateInput extends Component {

  constructor(props) {

    this.handleChange = this.handleChange.bind(this);

    this.state = {
      value: ''
    }

  }

  handleChange(val) {

    val = val.split('/').join('');
    val = val.match(new RegExp('.{1,2}', 'g')).join("/");

    this.setState({
        value: val
    });

  }


  render() {

    const {value} = this.state;
    const placeholder = 'DAY/MONTH/YEAR';

    return ( <input type = "text" value={value} placeholder={placeholder}
      onChange = {this.handleChange}/>
    );

  }

}
Share Improve this question edited May 23, 2017 at 12:32 CommunityBot 11 silver badge asked Mar 30, 2017 at 13:42 user7597670user7597670 4
  • Is this the whole code? – funcoding Commented Mar 30, 2017 at 14:05
  • updated code, but that should be everything needed for the question – user7597670 Commented Mar 30, 2017 at 14:07
  • I think I found a way! Check my answer – funcoding Commented Mar 30, 2017 at 14:39
  • @funcoding i dont want to add another library tbh. Thanks though, I appreciate your help – user7597670 Commented Mar 30, 2017 at 14:40
Add a ment  | 

3 Answers 3

Reset to default 3

You can set up an onKeyDown event on the input and detect for press of backspace. Similarly you can do it for delete too. I have demonstrated in the snippet below for backspace.

class DateInput extends React.Component {

  constructor(props) {
    super();
    this.handleChange = this.handleChange.bind(this);
     this.keyPressFunc = this.keyPressFunc.bind(this) 
    this.state = {
      value: ''
    }

  }
  keyPressFunc(e) {
   
    if(e.which === 8) {
      var val = this.state.value;
      console.log(val);
      if(val.length == 3 || val.length == 6) {
          val = val.slice(0, val.length-1);
          console.log(val)
          this.setState({value: val})
      }
    }
  }

  handleChange(e) {
    var val = e.target.value;
      console.log('called', val)
      if (val.length === 2) {

        val += '/';

      } else if (val.length === 5) {

        val += '/';

      }

      this.setState({
        value: val
      });

    
    
  }


  render() {

    const {value} = this.state;
    const placeholder = 'DAY / MONTH / YEAR';

    return ( <input type = "text" value={value} placeholder={placeholder}
      onChange = {this.handleChange} onKeyDown={this.keyPressFunc}/>
    );

  }

}
ReactDOM.render(<DateInput/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Your Issue: The issue in your code is in the handleChange function. When you try to delete the '/' the function gets called (because its bound to onChange) and adds a new '/' again.

Date inputs in general: Date-inputs can be very tricky as the formatting differs from country to country. Not only the seperator but also the order of day, month and year is different.

As I don't know what your Application is doing in the end I can't really give a straight answer here. If your Page/Application will be used not only in the US but around the world I would very much remend to use one of the many plugins out there to take care of your formatting issue.

For Example: https://github./RobinHerbots/Inputmask Demo here: http://robinherbots.github.io/Inputmask/

Hope this helps. Good luck and don't get to frustrated over date inputs (I've been there ;))

You could use the MaskInput: MaskedInput

var CustomInput = React.createClass({
  render() {
    return <MaskedInput
      mask="11-11-1111"
      placeholder="MM-DD-YYYY"
      size="11"
      {...this.props}
      formatCharacters={{
        'W': {
          validate(char) { return /\w/.test(char ) },
          transform(char) { return char.toUpperCase() }
        }
      }
    }/>
  }
})

class ShoppingList extends React.Component {
  render() {
    return (
      <div className="form-field">
        <label htmlFor="card">Card Number:</label>
        <CustomInput />
      </div>
    );
  }
}
ReactDOM.render(
  <ShoppingList />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg./[email protected]/umd/react-maskedinput.js"></script>
<div id="root"></div>

发布评论

评论列表(0)

  1. 暂无评论