0

I'm trying to add regex validation (or any better validation approach, if it exists) to validate time in the following format:

00:00:00:00 (hous:minutes:seconds:miliseconds)

none of the tutorials I saw online shows how to do this using angular 2. Can anybody point me to a nice tutorial or approach which I can follow to accomplish this?

Aiguo
  • 3,416
  • 7
  • 27
  • 52
  • This has nothing to do with Angular. What you are asking is basic Javascript (and regex). Look for a tutorial on basic regex with Javascript, then what you are trying to do will be very simple. I could give you the answer, but what does that help you? If you've never used regex, the answer would be so foreign to you, it would not benefit you except for this one case just to get the job done. – Paul Samsotha Nov 01 '16 at 01:05
  • Or if you really want to take the easy way out retag this question with [javascript] and [regex]. Guarnteed, answer within 5 minutes or less, or your money back – Paul Samsotha Nov 01 '16 at 01:06
  • 1
    I'll do it the hard way :) *searching for javascript regex tutorial online* thanks much @peeskillet – Aiguo Nov 01 '16 at 01:08

2 Answers2

1

Ill suggest you follow some standard like W3, you want something like this:

(?:(?:(?:(?<hh>\d{1,2})[:.])?(?<mm>\d{1,2})[:.])?(?<ss>\d{1,2})[:.])?(?<s>\d{1,2})

Its not the only answer and I encourage you to learn how to do it yourself. You can learn and test your regex expressions at https://regex101.com/

Franco
  • 848
  • 1
  • 12
  • 24
  • thanks @franco! but, how can I compare the input in the input field with the regex? – Aiguo Nov 01 '16 at 01:54
  • No problem! At the side bar you can see an explanation of the regex, and how the test field matches the test string. It event breaks it down in the different capture groups. – Franco Nov 01 '16 at 01:58
  • somehow, your doesn't seem to work in the regex tester. I created one myself: ^([01]?\d|2[0-3]):([0-5]?\d):([0-5]?\d):([0-9]?\d)$ and this does the job – Aiguo Nov 01 '16 at 02:02
  • Ahh! Maybe I misunderstood you, this one just checks the format and splits it on groups. You can add the number ranges so you cant go over 59 in minutes for example. Full match 0-11 `12:11:20:09` Group `hh` 0-2 `12` Group `mm` 3-5 `11` Group `ss` 6-8 `20` Group `s` 9-11 `09` – Franco Nov 01 '16 at 02:05
  • Whoops, hit enter before time. But the last part was the example. Glad you got yours working :) – Franco Nov 01 '16 at 02:07
  • this one was easy! now I have to figure out how to put this inside my code and make a comparison with the input field text and return true or false based on the matching – Aiguo Nov 01 '16 at 02:09
  • 1
    All you need to do is create a new RegExp(), and use the .filter() function from JS with a .match('your regexp') ;) – Franco Nov 01 '16 at 02:28
1

You can try the following regex pattern :

^((([0-1]?\d)|(2[0-3])):([0-5]?\d):([0-5]?\d):(\d?\d?\d))
Ashwin Kumar
  • 711
  • 5
  • 6