mns
mns

Reputation: 683

Need a Regular Expression for the validation of Time format

I have a datetime textbox which contains both date and time . I want to validate the time.For the date i have validated. e.g datetime value is 04/23/2013 05:26 pm;

I need a regex which can validate the time that will be in format 00:00:00 . all are digits and no special character or other than digits will be entered. i want only to validate dd:dd:dd all are 2 digits. I can enter for example 10:10:10 and 01:02.

i have tried with js way like this.i have no knowledge in regex.so i want suggestions.

function ValidateDate()
{
  //getting the value from textbox
  var dateVal=document.getElementById('txtDateTime').value;
  //after one space there is time..as i am using a datepicker and timepicker format
  var time=dateVal.split(' ')[1];   
  var isValidTime=CheckTime(time);
}


function CheckTime(time)
{
var timePart=time.split(":");
var hour = timePart[0];
var minute = timePart[1];
var second = timePart[2]; 


if((parseInt(hour,10)<0) || (parseInt(hour,10)>59))
{   
  return false;
}

if((parseInt(minute)>59) || (parseInt(minute)<0))
  {      
     return false;     

  }

 if((parseInt(second)<0) || (parseInt(second)>59))
  {
      return false;
  }  

  return true;
}

Thanks for your suggestions.

Upvotes: 0

Views: 1152

Answers (2)

h2ooooooo
h2ooooooo

Reputation: 39532

A simple regex of /^([0-1][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9]))?$/g will work.

10:00:00 - OK
01:00:00 - OK
60:00:00 - Fail
30       - Fail
30:00    - Fail
23:59    - OK
24:00    - Fail
23:60:60 - Fail
23:59:59 - OK

Regex autopsy:

  • ^ - This is where the sentence MUST start
  • ([0-1][0-9]|2[0-3])
    • [0-1][0-9] - The digits 0 to 1 followed by any digit between 0 and 9
    • | - OR
    • 2[0-3] - The digit 2 followed by any digit between 0 and 3
  • : - A literal : character
  • ([0-5][0-9]) - The digits from 0 to 5 followed by any digit between 0 and 9
  • (?::([0-5][0-9]))?
    • ?: - a non capturing group
    • : - A literal : character
    • ([0-5][0-9]) - The digits from 0 to 5 followed by any digit between 0 and 9
    • ? - means that the previous statement should be there 0 or 1 time (so it doesn't have to be there).
  • $ - This is where the sentence MUST end

Upvotes: 5

ShinTakezou
ShinTakezou

Reputation: 9671

The following regex should work: /^\d{2}:\d{2}(?::\d{2})?$/.

Upvotes: 0

Related Questions