0

I am building a realtime input validation for a date format. That is supposed to validate the date format while typing. In order to do that i need a regex to do the following: X is a number {0,9} and every step of the input needs to be valid.

I tried building a regex and finding one fitting but both without success. Best regards.

Valid Input Cases
"" - i.e empty
"X" - i.e. 3
"XX" - i.e. 31
"XX." - i.e. 31.
"XX.X" - i.e. 31.1
"XX.XX" - i.e. 31.10
"XX.XX." - i.e. 31.10.
"XX.XX.X" - i.e. 31.10.1
"XX.XX.XX" - i.e. 31.10.19
"XX.XX.XXX" - i.e. 31.10.199
"XX.XX.XXXX" - i.e. 31.10.1998

Edit: To clarify this will not replace date validation this will only be used in an HTML Input element in react to prevent the user from typing other chars.

Grifting
  • 57
  • 1
  • 9
  • I don't thing that regex is the best or even the correct solution here. Why? 1. It is because of February, it has 28 days normally but also sometimes 29 days. So to make sure that 29.02.2022 is a valid date cannot be solved by regex alone. 2. Every language today has built in functionality for parsing dates, so why trying to reimplement something that is built in in your language/runtime – Siraf Oct 09 '22 at 11:20
  • You are mistaken i will use that regex to format a text input and the date validation happens in the backend. I will just prevent the user from entering chars that don't belong there. – Grifting Oct 09 '22 at 11:34
  • so you have to do it in javascript in the client? – Siraf Oct 09 '22 at 11:35
  • Yes this validation is clientside to help the user enter the correct date format. – Grifting Oct 09 '22 at 11:37
  • have you checked this https://stackoverflow.com/questions/6177975/how-to-validate-date-with-format-mm-dd-yyyy-in-javascript ? there are 100% many java script libs that do what you want – Siraf Oct 09 '22 at 11:40
  • So you are not allowing the user after they have typed the whole thing to go back and delete `10` because they wanted `09` instead? What I am trying to say is: assuming that all users always type from left to right exclusively will fail. – Ole V.V. Oct 09 '22 at 13:27

0 Answers0