-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.

3
  • Remove new RegExp(' and the last '). Instead of (:|\.), use [:.] Commented Oct 22, 2020 at 13:27
  • @WiktorStribiżew I removed the characters you suggested. Now it looks like this: let regEx = /^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(:|\.)\d{2}?$/; the test still failed. Commented Oct 22, 2020 at 13:28
  • Yes, last digit matching pattern must be \d{1,2} or \d+. It depends on what your requirements are. Commented Oct 22, 2020 at 13:39

1 Answer 1

4

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'));

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

1 Comment

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 ???)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.