Ronald Ronald - 3 months ago 5
Javascript Question

How to Validate form in JQuery / Javascript

I am working with 4 text fields - the first 2 are jquery datepickers and the last 2 are times... I am trying to prevent time2 being greater than time1 only when the dates are equal...

The function is called when the submit button is onclick

Is there a cleaner way to do this? Something about this script doesn't look right to me? I feel like it has holes in it.

<script>


function empty() {

var x;
x = document.getElementById("date1").value;
if (x == "") {
alert("Enter a Valid Date!");
return false;
};

var y;
y = document.getElementById("date2").value;
if (y == "") {
alert("Enter a Valid Date!");
return false;
};


var val1 = $('#time1').val();
var val2 = $('#time2').val();

if (x == y) {

if (val1 >= val2) {
alert("Time 2 Needs to be Greater than the Time 1!");
$("#time2").focus();
return false;
}
};


}

</script>

Answer
function empty() {

    var date1 = $('#date1').val();
    var date2 = $('#date2').val();

    if ((date1 == "") || (date2 == "")) {
        alert("Date is required!");
    };

    var time1 = $('#time1').val();
    var time2 = $('#time2').val();

    if (date1 == date2) {
        if (time1 >= time2) {
            alert("Time 2 Needs to be Greater than the Time 1!");
            $("#time2").focus();
        }
    };
}
Comments