0

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>
1

2 Answers 2

1
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();
        }
    };
}
Sign up to request clarification or add additional context in comments.

Comments

0

And/or program your application with a framework like PHP's Laravel that makes form field validation easy: https://laravel.com/docs/5.3/validation

Frameworks provide you with a lot of code and an API that do the normal web things like form field validation (text, textarea, radio button, checkboxes, etc) for you. I use Laravel's functionality and don't hand code client-side or server-side validation any more.

2 Comments

Please don't add two answers. If you have something to add to your original answer, edit that answer.
@MikeMcCaughan, As an experienced programmer, when I need form field validation, I don't hand code JS form field validation at all any more. I answered his JavaScript question, but I also have such a fundamentally different solution to what he's doing/his problem, I thought it warranted a separate answer. :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.