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.

3
  • use document.getElementById('...').onChange = validateDate; Commented Apr 3, 2013 at 16:58
  • Tamil -Thanks for your quick response! I appreciate it. Commented Apr 3, 2013 at 17:00
  • Possible duplicate of How to validate date with format "mm/dd/yyyy" in JavaScript? Commented Dec 20, 2015 at 17:12

2 Answers 2

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

Comments

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.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.