Skip to main content
drslrb
Known Participant
February 1, 2025
Answered

Keystroke script for time in HHMM

  • February 1, 2025
  • 1 reply
  • 974 views

Hi.  I have a custom keystroke scipt to limit the text input field to numbers only.

if(!event.willCommit)
    event.rc = !isNaN(event.change) || (event.change == "-" && event.selStart == 0);
else
    event.rc = !isNaN(event.value);

I would also like to limit the input to 4 characters and restrict the first 2 digits to a number between 00 and 23 and the second 2 digits to a number between 00 and 59. 

 

Is there a way to split the 4 digit number into 2, to limit the input to achieve a time field with the format HHMM? 

var t1 = Number(start.substr(0,2)); 
var t2 = Number(start.substr(2,2));

 

Correct answer Nesa Nurani

I've attached a pdf with the fields.


Try this:

event.rc = /^\d{0,4}$/.test(event.value + event.change);

if (event.rc) {
 var newValue = event.value + event.change, len = newValue.length;
    
 if ((len >= 1 && newValue[0] > '2') || 
  (len >= 2 && parseInt(newValue.substring(0, 2), 10) > 23) || 
  (len >= 3 && newValue[2] > '5') || 
  (len == 4 && parseInt(newValue.substring(2, 4), 10) > 59)) {
  event.rc = false;}}

1 reply

Nesa Nurani
Community Expert
Community Expert
February 1, 2025

Why don't you use time format?

drslrb
drslrbAuthor
Known Participant
February 1, 2025

Thee's other fields on the PDF that uses the field for calculations.  The calculations don't work correctly when I use the time format.  They only work when I enter ####.

Nesa Nurani
Community Expert
Community Expert
February 1, 2025

Then use custom calculation, there are plenty of examples with scripts on the forum that calculate time.

If you tell us what you are trying to calculate, we can help you.