Domanda

I'm using this regex with

preg_match("/(2[0-3]|[01][0-9]):[0-5][0-9]/", $time)

It works fine with 05:00, etc (with 0 leading) but i would like to accept without the 0 like 5:00 since my mysql field is TIME and accept both i would like to let people give both, since they are going to do that.

Also this should accept 00:30 and of course not 24:30

È stato utile?

Soluzione

Try this: /^([01]?[0-9]|2[0-3])\:+[0-5][0-9]$/

01:00 valid
 5:00 valid
23:59 valid
30:00 invalid
24:00 invalid
00:00 valid
23:90 invalid

Just add the question mark really.

Altri suggerimenti

Just a wild guess by adding two question marks (optionals):

preg_match("/(2?[0-3]|[01]?[0-9]):[0-5][0-9]/", $time)

This should work as expected:

 preg_match("/^(2[0-3]|[01]?[0-9]):[0-5][0-9]$/", $inputToCheck)
  • Added ? to make the 0 or 1 prefix optional
  • Added ^ and $ to ensure the comparision uses the whole input
  • Allows 24 hour format restricted from 0:00 to 24:59
  • Allows both HH:MM and H:MM format
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top