2

I have a string with times (formatted HH:MM) each on a new line. I want to create a JS function to check if there is any times that does not belong. It should simply return true or false.

Example correct string: var s = "5:45\n07:00\n13:00\n17:00";

5:45
07:00
13:00
17:00

Example incorrect string: var s = "5:45\n07:00\n55:00\n17:00";

5:45
07:00
55:00 // incorrect date here, should return false
17:00

My regex experience is little to none. Playing around on Scriptular I created this expression to detect times that do match: /^[0-2]?[0-9]\:[0-5][0-9]$/m. This however is not sufficient.

So, how can I get this to work with a string s as indicated above?

function checkIfStringConforms(s)
{
  var all_good = [some magic with regex here]
  return all_good;
}

PS: I have Googled around and checked answers on SO. My regex skill is... eh.

3
  • So is 5:45 correct? H:MM is ok? Commented Feb 11, 2015 at 13:35
  • ^(?:[0-1]?[0-9]|2[0123]):[0-5][0-9]$ Commented Feb 11, 2015 at 13:38
  • @AlexK. Yes it is :) Commented Feb 11, 2015 at 14:58

3 Answers 3

1

Your regex is OK, but it would also match 29:00, so it needs some improvement. Then, it's always a bit more difficult to find non-matches than it is to find matches. You could try and remove all matches from the string and then see if it's empty (except for whitespace):

result = s.replace(/^(?:2[0-3]|[01]?[0-9]):[0-5][0-9]$/mg, "");

If result is empty after that, there were no illegal times in your string.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for also correcting my regex for checking that it is a legitimate time.
1

It can be done without the use of any regex. Just split on new-line and see if every date matches your format. For that we could use Array.every

function checkIfStringConforms(s) {
    return s.split("\n").every(function(str){
        var arr = str.split(":");
        return (arr[0] < 24 && arr[0] > -1) && arr[1] < (60 && arr[1] > -1)
    });
}

Comments

1

/(((2[^0-3]|[3-9].):..)|(..?:[^0-5].))(\n|$)/

Regexp returns true if your s var has at least one invalid time. Please, check it carefully before use – your question is quite broad and restrictions are not fully defined. Regex assumes that you have something like x:xx or xx:xx in each line (x is a digit) – I’m not sure this assumption covers all your data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.