-2

I have simple input on my html and i want to when user putting text value in the input value was automatically set by my regex pattern Example: I have time picker inputenter image description here and I want the user when he enters numbers, the value is automatically formatted in the input. How to do it with regex and replace function ?

I tried to do it this way, but in the end I just get the string that I enter.

console.log(value.replace(/^(([0-9]{1})|([0-1]{1}[0-9]{1})|([2]{1}[0-3]{1}))(([:]{1})?)(([0-5]{1}[0-9]?)?)$/g, ''));
Andre228
  • 7
  • 3

1 Answers1

0

If you are using a UI framework, refer to their documentation they would probably have a plugin to do it for you. Or if you want to do it on your own:

From the HTML side you can use type="time" attribute (please check the browser support for this).

And from JavaScript you can use something like ^([01]\d|2[0-3]):?([0-5]\d)$ on form submission for example.

const TIME_REGEX = /([01]\d|2[0-3]):?([0-5]\d)$/;

const myTimeElm = document.getElementById('myTime');
const outputElm = document.getElementById('output');

let timer;

outputElm.addEventListener('click', () => {
  if (TIME_REGEX.test(myTimeElm.value)) {
    outputElm.innerText = myTimeElm.value;
  } else {
    outputElm.innerText = "Error!"
  }
});
#output {
  cursor: pointer;
}
<input type="time" id="myTime" value="00:00">

<span id="output">click here!</span>

If you don't want to use HTML's type="time", consider using a mask for your input where you record the user's input and render the formatted output in a different component.

Since using the RegEx alone won't achieve the same user experience as you may want to workout the input's cursor position.

Or simple use a library that does that for you (Cleave.js for example)

Fcmam5
  • 4,888
  • 1
  • 16
  • 33