0

My goal is to validate a user-entered date in javascript.

I am basing my code on https://stackoverflow.com/a/6178341/3255963, but that code was designed to only validate mm/dd/yyyy.

if(!/^\d{2}\/\d{2}\/\d{4}$/.test(dateString))
    return false;

I want to also allow users to enter m/d/yyyy (in other words no leading zeros).

It appears the following works but I was wondering if there is a way to do this with regex in one line.

if(
    !/^\d{2}\/\d{2}\/\d{4}$/.test(dateString) && 
    !/^\d{1}\/\d{1}\/\d{4}$/.test(dateString) &&
    !/^\d{1}\/\d{2}\/\d{4}$/.test(dateString) &&
    !/^\d{2}\/\d{1}\/\d{4}$/.test(dateString)
  )
  return false;

PS Another portion of the linked script verifies other aspects of the input, but I'm not modifying that part.

Community
  • 1
  • 1
CarbonandH20
  • 361
  • 1
  • 3
  • 13

1 Answers1

0

You can specify minimum and the maximum number of characters to be matched, like this

if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))

Note: As @Matt suggested in the comments, using RegEx to validate date strings, is not a foolproof way.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497