Reputation: 373
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
Upvotes: 3
Views: 647
Reputation: 22794
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)">
Upvotes: 2
Reputation: 373
With all your help I produced the following:
function validate(e) {
var regexp = /([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]/;
if ((e.value.search(regexp) >= 0)) {
e.value.length == 4 ? document.getElementById(e.id).value = '0' + e.value : 0;
} else {
alert('Time is not entered correctly, enter like hh:mm');
}
}
<div>
<label for="name">Time</label>
<input id="lbl3" class='input' type="text" onchange="validate(this);">
</div>
Upvotes: 0
Reputation: 10476
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();">
Upvotes: 1
Reputation: 465
First, you should change your regexp so it'll be able to validate both cases with and without leading zeros. If the input is valid you can modify the input with one of the offered solutions or any other.
Upvotes: -1