Reputation: 371
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'
Upvotes: 1
Views: 879
Reputation: 13702
Note that your onChange will have dashes as well. So just remove unwanted -
before you apply regex and also remove unwanted -
when you set state
Working copy of your code is here
Like this
export default function App() {
const [expiry, setExpiry] = useState();
const formatValue = e => {
const val = e.target.value.replace(/-/gi, "");
const formattedDate = val.replace(/^(\d{2})(\d{0,2})(\d{0,4})/, `$1-$2-$3`);
setExpiry(formattedDate.replace(/-$|--$/gi, ""));
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<input value={expiry} onChange={formatValue} />
</div>
);
}
Upvotes: 1