0

I need to make JavaScript function to validate date that users put inside input field. The valid date format needs to be yyyyMMdd. How to write regex code to validate this input date format? This date formats are valid: 2019/12/01 and 2019-12-01. All other formats are not allowed.

Dusan
  • 11
  • 2
  • 1
    Why would you want the user to type all that out, unless you're literally testing their ability to type dates? Just make a date field. – CAustin Dec 05 '19 at 23:18
  • 1
    You'll need more than regex - since months have different number of days, and one month doesn't have consistent number of days ... so, sure, use regex to make a preliminary validation `/^(\d{4})[/-](0[1-9]|1[0-2])[/-](0[1-9]|[12]\d|3[01])$/` but then you'll want code to validate dates above 28 since that's where the inconsistencies lie - and since you'll be validating using code, you may as well use just a simple `/^(\d{4})[/-](\d\d)[/-](\d\d)$/` for the prelim validation – Jaromanda X Dec 05 '19 at 23:38
  • date validation with regex is a bit tricky. you should double check both the _format_ and then do some validation on the values. I.e. `2019-02-30` is valid based on format, but fails any other check because february does not have 30 days in 2019 (or, you know, ever?) – Jhecht Dec 06 '19 at 00:06

2 Answers2

1

This is interesting topic... it starting with simple solution:

\d{4}(-|\/)\d{2}\1\d{2}

In this solution we are having 4 numbers than - or /, than 2 numbers, than delimiter used before (- or /) and than 2 more numbers... which is much better solution than

\d{4}[-\/]\d{2}[-\/]\d{2}

because in second one 2019-12/01 will pass validation, in first one will not pass...

but when you brainstorm more on that topic... you probably want validation to be even smarter than that so next step will be

[12]\d{3}(-|\/)\d{2}\1\d{2}

on this way year must start with 1 or 2... than sky is the limit what else you will include...

Sorry for too much writing but validation is always interesting topic

Sinisa Bobic
  • 1,311
  • 10
  • 15
0

I need to make JavaScript function to validate date that users put inside input field.

If you can, you might be better off using <input type="date"> instead.

Working Example:

<input type="date">
Rounin
  • 27,134
  • 9
  • 83
  • 108