I have a text box which accepts time(max of 5 characters only), and a drop down which accepts am or pm value.
I need to perform some validations for the string values entered into the text box such as:
- If user enters 9 => Should be changed to 0900
- 9:3 => 0930
- 09:3 => 0930
- 93 => alert (‘Invalid Hours value)
- 115 => 0115
- 12 => 1200
- Invalid entries such as !@#$%^&*()<>?/~`,;'”[]_-abcdefg.. => alert (‘Invalid Time Value’) should be displayed.
So far, all I’ve achieved is replacing the : with ”.
For example, if user enters 09:00 => 0900
I need something like:
if clks is 1 digit, then rightpad clks with 2 zeroes.
if 2 digits: clks > 12 , then alert(Invalid hours value)
if 3 digits: clks < (%59) (i.e checking last 2 chars) , then leftpad with 1 zero
or clks > (%59) , then alert (‘Invalid minutes value)
if 4 digits: clks>12% (checking first 2 chars), alert (‘invalid hours value’)
or (clks>12% and clks>59%) , then alert(‘invalid clock time’)
or (clks<12%) and (clks<59%) , then accept the number as it is.
if 5 digits: (and all are numbers), then alert(‘invalid clk time’)
These validations need to be done within script tag. (The backend language that I’ve used is jsp.)
Pls help me 🙁
Here is a part of the code that I have written:
<script type='text/javascript'>
function clocks(){
var clk = document.getElementById('TIME').value;
var clks = clk.replace('/:/g','');
var ampm = document.getElementById('AMPM').value;
var add = 1200;
if (clks=="")
{
alert("You must enter clock time");
}
else
{
if (ampm=='p')
{
clks=parseFloat(clks) + parseFloat(add);
}
}
}
....
</script>
Here’s a way to do it in a function:
To call it, you’d do:
and your result would be an object passed back… result.clks is the padded time, and result.is_valid will either be a true or false value as to whether the input time is valid or not.