user656523
user656523

Reputation: 3361

Regex validation for time entries

I have a text box which accepts time in the format HH:mm and entries should only be in 24-hour format.For all invalid entries, a common message 'Invalid entry' should be displayed.

For eg:

19:61 //INVALID
12:00am //INVALID
12***M //INVALID

06:00 //VALID
22:00 //VALID
5:45 //VALID

The code required is in Java. Not familiar with regex expressions...so need your ideas on it.Thx in advance! :)

String timeStr = getTimeBoxValue();

Upvotes: 2

Views: 6047

Answers (2)

Alderath
Alderath

Reputation: 3859

Too explain the regex in ash108:s comment:

^(([0-9])|([0-1][0-9])|([2][0-3])):(([0-9])|([0-5][0-9]))$

^ at the beginning of the string...

([0-9])|([0-1][0-9])|([2][0-3]) ...there must be a number 0-9 OR a (number with first 0-1 and then 0-9) OR (a number with first 2 and then 0-3)

: then there must be a : sign

([0-9])|([0-5][0-9]) then there must be a number 0-9 OR a (number with first 0-5 and then 0-9)

$ and then there must be the end of the string

There is one thing a bit weird with this expression though, if you examine it. Look at the part after the : sign. It will allow a single digit 0-9. Hence a string as for example 12:5 would be valid. Imo this part should probably be removed resulting in:

^(([0-9])|([0-1][0-9])|([2][0-3])):([0-5][0-9])$

Now, the part after the : sign is forced to have two digits, while the part before the : sign can have either one or two digits.

Upvotes: 2

jiten
jiten

Reputation: 5264

There is a Link Which you can use.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Time24HoursValidator{

  private Pattern pattern;
  private Matcher matcher;

  private static final String TIME24HOURS_PATTERN = 
             "([01]?[0-9]|2[0-3]):[0-5][0-9]";

  public Time24HoursValidator(){
      pattern = Pattern.compile(TIME24HOURS_PATTERN);
  }

  /**
   * Validate time in 24 hours format with regular expression
   * @param time time address for validation
   * @return true valid time fromat, false invalid time format
   */
  public boolean validate(final String time){

      matcher = pattern.matcher(time);
      return matcher.matches();

  }
}

Upvotes: 5

Related Questions