-1

Im trying to validate a form that checks for valid running distance times, so i want it to allow times with single digits for minutes i.e. 2:55, or 12:55 would both pass the validation. Here is what i've come up with but it only works for 1 digit minutes.

/^\d:[0-5]\d$/

How do i change this to allow also the 2 digit minutes?

croc_hunter
  • 285
  • 3
  • 12
  • Can you tell what programming language you are using and maybe what library you are using? – EvensF Dec 03 '17 at 20:24
  • javascript. but this is just a part of the pattern variable of a form input – croc_hunter Dec 03 '17 at 20:43
  • Possible duplicate of [Regular expression to validate valid time](https://stackoverflow.com/questions/884848/regular-expression-to-validate-valid-time) – roydukkey Dec 05 '17 at 06:04

2 Answers2

0

Looking at your answer I think you should use instead

/^[0-5]?\d:[0-5]\d/

Here's an interactive example :

<!DOCTYPE html>
<html>
    <head>
        <title>Form validation</title>
    </head>
    <body>
        <h1>Form validation question</h1>
        <p>This is an example that shows test answers for the question</p>
        <form name="example">
            <input onchange="updateResult(this.value)" /><br />
            <p id="result"></p>
        </form>
         <script>
            function updateResult(text_entered){
                var output_text_element = document.getElementById("result");
                var pattern = /^[0-5]?\d:[0-5]\d/;
                if (pattern.test(text_entered)) {
                    output_text_element.innerHTML = "Valid time";
                } else {
                    output_text_element.innerHTML = "Invalid time";
                }
            };     
        </script>
   </body>
</html> 

This code says:

  • Valid time for 2:34
  • Valid time for 32:34
  • Invalid time for 32:64
  • Invalid time for 82:64
  • Invalid time for 82:14
EvensF
  • 1,479
  • 1
  • 10
  • 17
  • no neither of those works. The first one fails if you enter a 2 digit minute, and the second one fails in both scenarios – croc_hunter Dec 03 '17 at 19:11
0

OK i worked it out. Here is the answer for anyone thats looking for a solution in the future

(([0-5][0-9])|([0-9]))(:[0-5][0-9])
croc_hunter
  • 285
  • 3
  • 12