I have an input box in a React component. 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 complete React component 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}/>
);
}
}