Link to home
Start Free TrialLog in
Avatar of rtis1
rtis1

asked on

Javascript Validation problem: Validate if one field is greater than another

Hello all,

I know there is a simple answer to this, but I have been having problems validating of one field is graeter than another.
The form is pretty simple and in it I have two select fields: StartTime and EndTime as follows:

<select name="CallStart">
<option value="">---</option>
<option value=8>8AM</option>
<option value=9>9AM</option>
<option value=10>10AM</option>
<option value=11>11AM</option>
<option value=12>12PM</option>
<option value=13>1PM</option>
<option value=14>2PM</option>
<option value=15>3PM</option>
<option value=16>4PM</option>
<option value=17>5PM</option>
<option value=18>6PM</option>
<option value=19>7PM</option>
<option value=20>8PM</option>
<option value=21>9PM</option>
<option value=22>10PM</option>
</select>

<select name="CallEnd" >
<option value="">---</option>
<option value=8>8AM</option>
<option value=9>9AM</option>
<option value=10>10AM</option>
<option value=11>11AM</option>
<option value=12>12PM</option>
<option value=13>1PM</option>
<option value=14>2PM</option>
<option value=15>3PM</option>
<option value=16>4PM</option>
<option value=17>5PM</option>
<option value=18>6PM</option>
<option value=19>7PM</option>
<option value=20>8PM</option>
<option value=21>9PM</option>
<option value=22>10PM</option>
</select>

I need to ensure that the CallStart time is not greater than the CallEnd time and I used the following Javascript validation:

    if (myform.tel1_callstart.value > myform.tel1_callend.value)
  {
    alert('Your preferred call start time cannot be later than your call end time".');
    myform.tel1_callstart.focus();
    return (false);
  }

However this does not seem to work and I'm not sure what i'm doing wrong.
Avatar of hongjun
hongjun
Flag of Singapore image

You should do something like this

<script>
function validate(myform) {
    if (myform.tel1_callstart.value > myform.tel1_callend.value)
  {
    alert('Your preferred call start time cannot be later than your call end time".');
    myform.tel1_callstart.focus();
    return (false);
  }

    return true;
}


<form onsubmit="return validate(this)">
<select....
....

</form>
Avatar of Michel Plungjan
Numerically correct, but a string of 2 is greater than 19

  var val1 = parseInt(myform.tel1_callstart.options[myform.tel1_callstart.selectedIndex].value,10)
  var val2 = parseInt(myform.tel2_callstart.options[myform.tel2_callstart.selectedIndex].value,10)
  if (val1> val2) {
    alert('Your preferred call start time cannot be later than your call end time.');
    myform.tel1_callstart.focus();
    return (false);
  }
ASKER CERTIFIED SOLUTION
Avatar of third
third
Flag of Philippines image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial