I am currently grappling with time validation and feeling a bit perplexed about how to effectively validate both the start_time
and end_time
using &&. Here is the code I have been working on:
var re = /^(\d{1,2}):(\d{2})([ap]m)?$/;
//Start Time
if($('.start_time').val() != '') {
if(regs = $('.start_time').val().match(re)) {
if(regs[3]) {
// 12-hour value between 1 and 12
if(regs[1] < 1 || regs[1] > 12) {
$('.start_time_error').html('<div>Invalid value for hour(s)</div>');
$('.start_time').focus();
return false;
}
} else {
if(regs[1] > 12){
$('.start_time_error').html('<div>Invalid value for hour(s)</div>');
return false;
}
}
// minute value between 0 and 59
if(regs[2] > 59) {
$('.start_time_error').html('<div>Invalid value for minute(s)</div>');
$('.start_time').val().focus();
return false;
}
} else {
$('.start_time_error').html('<div>Invalid time format</div>');
$('.start_time').focus();
return false;
}
$('.start_time_error').html('<div>Checked</div>');
return true;
}else{
$('.start_time_error').html('<div>Please fill up</div>');
return false;
}
//End time----------
if($('.end_time').val() != '') {
if(regs = $('.end_time').val().match(re)) {
if(regs[3]) {
// 12-hour value between 1 and 12
if(regs[1] < 1 || regs[1] > 12) {
$('.end_time_error').html('<div>Invalid value for hour(s)</div>');
$('.end_time').focus();
return false;
}
} else {
if(regs[1] > 12){
$('.end_time_error').html('<div>Invalid value for hour(s)</div>');
return false;
}
}
// minute value between 0 and 59
if(regs[2] > 59) {
$('.end_time_error').html('<div>Invalid value for minute(s)</div>');
$('.end_time').val().focus();
return false;
}
} else {
$('.end_time_error').html('<div>Invalid time format</div>');
$('.end_time').focus();
return false;
}
$('.end_time_error').html('<div>Checked</div>');
return true;
}else{
$('.end_time_error').html('<div>Please fill up</div>');
return false;
}
I attempted to use something like:
if(regs = $('.start_time').val().match(re) && regss == $('.end_time').val().match(re) )
However, it did not work as expected and resulted in an error "regss is not defined
". Are there any alternative approaches you could suggest? Thank you!