-1

I created function that should validate user input. The value should only be accepted as valid if format is matching this hh:mm:ss.s. Here is the function:

function time_format(time_val) {
   let regEx = new RegExp('/^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(:|\.)\d{2}?$/');
   console.log(time_val);
   console.log(regEx.test(time_val));
};

console.log(time_format('00:00:00.0'));
console.log(time_format('05:35:23.7'));
console.log(time_format('25:17:07.0'));

All three values failed the test above. First and second format should pass the regex. The third should fail since the hours are not valid. If anyone knows how this can be fixed please let me know.

espresso_coffee
  • 5,980
  • 11
  • 83
  • 193

1 Answers1

3

Try this…

function time_format(time_val) {
   let regEx = /^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(:|\.)\d{1,2}?$/;
   console.log(time_val);
   console.log(regEx.test(time_val));
};

console.log(time_format('00:00:00.0'));
console.log(time_format('05:35:23.7'));
console.log(time_format('25:17:07.0'));
Guile
  • 1,473
  • 1
  • 12
  • 20
  • Thanks. A little rejigging of the last part, and it now reads milliseconds to 3 digits. (Downloaded a regex from another site, and it ran out of memory / corrupted Firefox profile / made Windows take 15mins to boot ! (It also took out my wireless dongle - or did that failing take out everything else ???) – Cristofayre May 11 '23 at 14:19