I'm trying to validate an input field in which I set the date and time using a datetime picker. How can I add h:m to the pattern of the field so it's like dd.mm.yyyy hh:ii?

<form method="post">
  <input type="text" name="startDate" id="sDate" placeholder="Insert date..." pattern="(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}">
  <input type="submit" name="search" id="search" value="Search">

3 Answers

ghr On Best Solutions

Assuming you want each part of the date/time in a capture group:

(0[1-9]|1[0-9]|2[0-9]|3[01])\.(0[1-9]|1[012])\.([0-9]{4}) ([0-1][0-9]|2[0-3]):([0-5][0-9])

Demo: https://regex101.com/r/XkTfwo/11

Shortened the date part:

(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[0-2])\.([0-9]{4}) ([0-1][0-9]|2[0-3]):([0-5][0-9])


Marcus On

The following should do:

(0[1-9]|[12][0-9]|3[0-1])\.(0[1-9]|1[0-2])\.([0-9]{4}) ([0-1][0-9]|2[0-3]):([0-5][0-9])

Here you can try it: https://regex101.com/r/XkTfwo/10

Community On

the pattern attribute on a HTML <input /> accepts a regular expression. Therefore one would need to create a regular expression for dd.mm.yyyy hh:ii. For example, a very rudimentary one could be (doesn't check that the month isn't between 01 and 12):

[0-9]{2}\.[0-9]{2}\.[0-9]{4} [0-9]{2}:[0-9]{2}

Please see w3schools' tryit.

EDIT: Note the escaped periods. These are necessary. See @glhr's answer for the enforcement of valid numbers for the fields (i.e. 01-12 for mm).