0

In Javascript I am trying to write the validation for a date, where the user has to select a future date and not a past date. My code seems to work only when I use a date from last month (e.g. 26/11/2011). This is my script:

<script type="text/javascript" >
 function mydate()
 { 
 var d= new Date ();
 var day= d.getDate ();
 var mon=d.getMonth ();
 var year= d.getFullYear ();
 var dateformat= day+"/"+mon+"/"+year ;
 var get= document.getElementById("txt").value; 
 if(get >= dateformat )
 {
 alert ('yes valid');
 }
 else 
 {
 alert('Date should greater than to date ');
 }
 }
</script> 
bobbymcr
24.3k3 gold badges59 silver badges68 bronze badges
asked Dec 26, 2011 at 4:54

1 Answer 1

2

You are comparing the date values as strings. This is a textual comparison not a date-wise comparison so it will pretty much never work except by coincidence. You need to parse the date value the user enters into a Date data type and do a comparison that way.

Whenever possible you should avoid writing date manipulation code yourself and try to leverage a known working solution, e.g. the jQuery UI Datepicker.

answered Dec 26, 2011 at 5:02
Sign up to request clarification or add additional context in comments.

2 Comments

Mr. bobbymcr can we place both javascript and asp.net validation controls in the same page for different controls.
I am neither a Javascript nor ASP.NET expert, but I'm pretty sure you can do it. You may run into difficulties, e.g. see here: stackoverflow.com/questions/4088770/…

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.