Skip to main content
drslrb
Known Participant
Feb 1, 2025 5:07 AM UTC
Answered

Keystroke script for time in HHMM

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

 

Nesa Nurani
Nesa NuraniCorrect answer
Community Expert
Feb 1, 2025 3:45 PM UTC

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;}}

8 replies

Nesa Nurani
Community Expert
Community Expert
Feb 1, 2025 7:22 AM UTC

Why don't you use time format?

Translate
drslrb
drslrbAuthor
Known Participant
Feb 1, 2025 10:10 AM UTC

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

Translate
Nesa Nurani
Community Expert
Community Expert
Feb 1, 2025 12:13 PM UTC

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.

Translate