1

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'
3
  • 1
    Please add sample input and output to make your problem reproducible. Commented May 27, 2020 at 1:59
  • you'll most likely need to post the event listener and preferably your HTML too. I'm guessing you're using some kind of regex replace on input.value on input? You'll probably have to restore selection positions for it to work right. Also \d doesn't include spaces nor - Commented May 27, 2020 at 2:03
  • @TimBiegeleisen Ive added an example of what I want to happen. Commented May 27, 2020 at 2:14

1 Answer 1

1

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>
  );
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.