简体   繁体   English

使用javascript验证日期?

[英]Date validation using javascript?

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. 在Javascript中,我试图为日期编写验证,用户必须选择未来的日期而不是过去的日期。 My code seems to work only when I use a date from last month (eg 26/11/2011 ). 我的代码似乎只在我使用上个月的日期时才有用(例如26/11/2011月26日)。 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> 

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. 您需要解析用户输入的日期值到Date数据类型并以这种方式进行比较。

Whenever possible you should avoid writing date manipulation code yourself and try to leverage a known working solution, eg the jQuery UI Datepicker . 只要有可能,您应该避免自己编写日期操作代码并尝试利用已知的工作解决方案,例如jQuery UI Datepicker

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM