0

I have a input field date in my form and would like to add Javascript validation to ensure that its always greater than today's date. I tried the following but the function doesnt seem to be called when the user clicks on the input field and makes a change.

<input type="text" name="InsertRecordGuestOrders_Delivery_date" id="InsertRecordGuestOrders_Delivery_date" value=""/>

<script type="text/javascript">

function validateDate()
{
var del_date = document.getElementById('InsertRecordGuestOrders_Delivery_date').value;

if (Date.parse(del_date) < Date.now()) {
    document.getElementById('InsertRecordGuestOrders_Delivery_date').value = '';
    alert("Delivery date has to be later than today");
    }
}

document.getElementById('InsertRecordGuestOrders_Delivery_date').onChange = validateDate();

</script>

Any suggestions on what I'm doing wrong?

Thanks in advance.

Maverick
  • 61
  • 3
  • 10

2 Answers2

5

You want to assign the validateDate function to the onchange property, not execute the function and assign its return value. Change this:

document.getElementById('...').onChange = validateDate();

to this:

document.getElementById('...').onChange = validateDate;
jbabey
  • 45,965
  • 12
  • 71
  • 94
1

This line:

document.getElementById('InsertRecordGuestOrders_Delivery_date').onChange = validateDate();

Should be:

document.getElementById('InsertRecordGuestOrders_Delivery_date').onchange = validateDate;

Notice the parentheses are gone. If you invoke it immediately, you're assigning the return value of validateDate() as the onchange handler. You want to assign the function itself as the handler, not the return value of the function.

In addition, it should be onchange, not onChange.

Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
  • 1
    By the way, good catch on the "onchange". I tried it out in JsFiddle and it didnt work until I changed "onChange" -> "onchange". Appreciate the help! Thanks again! – Maverick Apr 03 '13 at 17:24