I have a date input (string) that I am trying to format so when I send it to the DB it is in the correct format. That format I want is DD-MM-YYYY.
Ideally I want to add the '-' dynamically as the code reaches the relevant points ie after DD and MM.
My current code is:
const formattedDate = date.replace(
/^(\d{2})(\d{0,2})(\d{0,4})/,
`$1-$2-$3`,
);
It works fine when I input the numbers, but when I try to backspace it wont go past the first '-'.
I understand why it is doing this (my regex adds the '-' every time there is a change to the string), but I cant work out a solution.
const [expiry, setExpiry] = useState<string>();
const formatValue = () => {
/^(\d{2})(\d{0,2})(\d{0,4})/,
`$1-$2-$3`,
);
setExpiry(formattedDate);
}
<TextInput value={expiry} onChange={formatValue} />
Sample inputs and outputs:
input0 - '2'
output0 - '2'
input1 - '22'
output1 - '22-'
input2 - '220'
output2 - '22-0'
etc
finalInput - '22022022'
finalOutput - '22-02-2022'
\ddoesn't include spaces nor-