JS检查有效的日期格式 [英] JS check for valid date format

查看:264
本文介绍了JS检查有效的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本字段,用户输入的日期时间格式为: dd / mm / YYYY hh:ii 。我想检查这是否是一个有效的日期时间使用javascript。这应该包括二月二十九日和一切。我怎样才能做到这一点?由于特殊的月份,正则表达式将无法成功。

I have a text field where a user inputs a date-time in the format: dd/mm/YYYY hh:ii. I want to check if this is a valid date-time using javascript. This should include 29th of february and everything. How can I do that? A regex won't succeed due to special months.

推荐答案

请参阅 http://internotredici.com/article/checkdateinjavascript/ ,以获取有用的文章,检查时间 - 只是你想要的!

see http://internotredici.com/article/checkdateinjavascript/ for a helpful article on checking the time - just what you want!

下面是文章的全文

在javascript
中查看日期2006年1月31日发布的脚本
程序员非常经常需要验证插入表单的信息,并检查其正确性是有用的,从javascript中获益。本教程将介绍如何使用javascript来验证日期是否有效。
表单中的日期以两种不同的方式插入,首先使用用户类型数据遵循不同模式的文本字段(在本教程中,我们假定日期为dd-mm-yyyy格式);第二个使用而不是下拉菜单。第一个解决方案更容易实现,但是受到用户更多的错误(例如,插入无效字符或更频繁的打字日期与不同于已计划的格式)。
假设我们现在有以下文本字段,其中我们要以dd-mm-yyyy格式插入日期:

Check date in javascript Article published on January 31, 2006 under Scripting Programmers very often needs to validate informations inserted into forms and to check their correctness is useful take advantage from javascript. This tutorial will explain how to use javascript in order to verify if a date is valid or not. Dates in forms are inserted in two different ways, the first uses a text field where user type data following different patterns (in this tutorial we assume that dates are in dd-mm-yyyy format); the second uses instead pulldown menus. The first solution is more simple to carry out, but is subject to more errors by users (for example inserting invalid characters or more frequent typing dates in a format different from the one that have been planned). Suppose now that we have the following text field in which we want to insert a date in dd-mm-yyyy format:

<form id="test_form" action="get" method="/checkdatejavascript" 
onsubmit="return(check_form(this)); return false;">
<input type="text" name="datefield" id="datefield" />
</form>

要检查插入数据的正确性,我们将使用check_form函数:

To check the correctness of inserted data we will use the check_form function:

function check_form()
{
// Regular expression used to check if date is in correct format
var pattern = new RegExp([0-3][0-9]-(0|1)[0-9]-(19|20)[0-9]{2});
if(document.getElementById('datefield').value.match(pattern))
{
  var date_array = document.getElementById('datefield')
                   .value.split('-');
  var day = date_array[0];

  // Attention! Javascript consider months in the range 0 - 11
  var month = date_array[1] - 1;
  var year = date_array[2];

  // This instruction will create a date object
  source_date = new Date(year,month,day);

  if(year != source_date.getFullYear())
  {
     alert('Year is not valid!');
     return false;
  }

  if(month != source_date.getMonth())
  {
     alert('Month is not valid!');
     return false;
  }

  if(day != source_date.getDate())
  {
     alert('Day is not valid!');
     return false;
  }
}
else
{
  alert('Date format is not valid!');
  return false;
}

return true;

}
我们可以看到,蓝色证明的正则表达式用于控制是否插入的日期遵循或不是默认分配的格式。如果模式有效,则函数进行到下一步,否则会出现错误信息abd form不发送(正则表达式,而且日期不能为空)。
要验证日期,我们将使用javascript提供的Date对象。 (检查红色证明的代码)。该算法很简单。使用用户插入的信息,我们将创建一个Date对象,并使用getFullYear,getMonth和getDate方法,我们将生成三个值,分别表示与之相关的年份,月份和日期。如果这些值与用户插入的值相等,那么日期是正确的。现在考虑以下示例:

} As we can see, the regular expression evidenced in blue is use to control if inserted date follows or not the default assigned format. If the pattern is valid then function proceed to the next step otherwise an error message is raised abd form is not sent (the regular expression guarantees moreover that date cannot be empty). To validate the date we will use the Date object offered by javascript. (check the code evidenced in red). The algorithm is pretty simple. Using the informations inserted by user we will create a Date object and using the methods getFullYear, getMonth and getDate we will produce three values representing respectively the year, the month and the day associated to it. If these values are equal to those inserted by user, then the date is correct. Consider now the following examples:

用户在文本字段中插入字符串09-01-1976
从字符串创建的日期对象为09-01-1976
日期有效

User insert in text field the string 09-01-1976 Date object created from string is 09-01-1976 Date is valid

用户在文本字段中插入字符串31-02-2006
从字符串创建的日期对象为03-03-2006
日期无效

User insert in text field the string 31-02-2006 Date object created from string is 03-03-2006 Date is not valid

程序员必须特别注意(检查绿色证明的代码),以JavaScript处理日期的方式,因为月份被认为在0到11,假设o是1月11日是12月。
如果下拉菜单用于插入日期,则控件更简单,因为正则表达式不需要验证日期格式:

Programmer had to take particular attention (check the code evidenced in green) in the way javascript handles dates, because months are considered in the range from 0 to 11 assuming that o is January and 11 is December. In case of pulldown menus are used to insert dates, controls are more simple due to the fact that regular expression is not need to validate date format:

  <form id="test_form" action="get" method="/checkdatejavascript" 
   onsubmit="return(check_form(this)); return false;">
  <select name="dateday" id="dateday">
  <option value="1">1</option>
     […]
  </select>
  <select name="datemonth" id="datemonth">
  <option value="0">January</option>
     […]
   </select>
   <select name="dateyear" id="dateyear">
  <option value="2006">2006</option>
     […]
  </select>
  </form>

将控制日期正确的javascript函数是

The javascript function that will controll date correctness is

 function check_form()
{
 var day = document.getElementById('dateday').value;
 var month = document.getElementById('datemonth').value;
 var year = document.getElementById('dateyear').value;

 // This instruction will create a date object
 source_date = new Date(year,month,day);

 if(year != source_date.getFullYear())
{
   alert('Year is not valid!');
   return false;
}

if(month != source_date.getMonth())
{
  alert('Month is not valid!');
  return false;
}

if(day != source_date.getDate())
{
  alert('Day is not valid!');
  return false;
}

 return true;
}

更新:我更新了代码,因为常规问题表达。感谢Alex的建议

Update: I have updated the code, because there was an issue with the regular expression. Thanks to Alex for the advice

这篇关于JS检查有效的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆