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> 

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.

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

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.