Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I auto-insert a leading zero in Time notation

The following code checks if the user inserted a correct time notation in a textbox. If the notation is not correct an alert box will be shown.

It also shows an alert if a leading zero is forgotten (i.e. 7:45 iso 07:45)

function validateThis(e){
    //INPUT VALIDATION
        var regexp = /([01][0-9]|[02][0-3]):[0-5][0-9]/; //CORRECT TIME FORMAT
        var correct = (e.value.search(regexp) >= 0) ? true : alert('Enter time as hh:mm (13:25)');
    }

My question is how can I auto-insert a leading zero if forgotten rather than notifying the user

like image 639
Dummy Avatar asked Jan 28 '26 06:01

Dummy


2 Answers

You can compare the number (if string, convert it to number) with 10, if it's less than 10, add a zero, else, keep it as-is:

note: You can just split the string at colons and check for validity, no need for a regex.

function leadZero(n) {
  return n < 10 ? "0" + n : n; 
}

function validateThis(e) {
  var hhmm = e.value.split(':'); // split into hh, mm
  // if there are two values (hh, mm) and
  // 0<=hh<=23 and 0<=mm<=59 => correct time
  
  var correct = false;
  
  if (hhmm.length === 2) {
    var [hh, mm] = hhmm;
    
    [hh, mm] = [+hh, +mm]; // +n in case of string, +n converts it to a number
    
    if ((hh>=0 && 23>=hh) && (mm>=0 && 59>=mm)) { // valid time
      correct = true;
    }
  }
  
  if (correct) {
    // add leading zeros
    //               fix hour                 fix minute
    var newTime = leadZero(hh) + ':' + leadZero(mm);
    console.log(newTime);
  } else {
    alert('Enter a valid time only');
  }
}
<input type="text" onchange="validateThis(this)">
like image 127
MrGeek Avatar answered Jan 30 '26 18:01

MrGeek


You may try the following approach:

function verify()
{

var str=$("#time").val();
var patt = new RegExp("^(0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$");

if(patt.test(str))
  {
    if(str.length==4)
      $("#time").val("0"+str);
    console.log("true");
  }
else
  console.log("false");



}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" name="time" id="time" value="" />
<input type="button" name="sbmt" id="sbmt" value="Submit" onclick="verify();">
like image 33
Rizwan M.Tuman Avatar answered Jan 30 '26 18:01

Rizwan M.Tuman