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}/>
);
}
}
You could use the MaskInput: MaskedInput
You can set up an
onKeyDown
event on the input and detect for press ofbackspace
. Similarly you can do it for delete too. I havedemonstrated
in the snippet below for backspace.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 recommend to use one of the many plugins out there to take care of your formatting issue.
For Example: https://github.com/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 ;))