I am trying to implement date field similar to this page with date format of yyyy/mm/dd
in react.
This is what i have tried
const [date_of_birth,setDateofBirth] = useState("");
const handleChangeDOB = (e) => {
let value = e.target.value;
value = value.replace(/D/g, "");
if(value.length >= 6){
value = `${value.slice(0, 4)}/${value.slice(4, 6)}/${value.slice(6)}`;
}
else if(value.length >= 4){
value = `${value.slice(0, 4)}/${value.slice(4)}`;
}
setDateofBirth(value);
}
<input type="text" maxLength={10} value={date_of_birth} onChange={handleChangeDOB} placeholder="yyyy/mm/dd"/>
When ever i try to delete it does not work correctly. If delete from in between then there can be two slash. What else I have to do to make it work ?
3
Answers
Is this solution enough: https://codesandbox.io/s/strange-engelbart-0pcpep?file=/src/App.js
Im using the react-input-mask to handle the masking logic.
The docs for the component are here: https://www.npmjs.com/package/react-input-mask
Well, Here is what you can do.
This is for checking value function.
And here is the event listener for your input.
I hope this will work for you.