2012-01-30 59 views
0

我想验证在客户端应该使用“mm/dd/yyyy”格式的BirthDate。Javascript日期datetime对于asp.net中的mm/dd/yyyy格式验证

我已经尝试过了如下,但它不能正常工作:

$("#btnUpdateEditCB3").click(function(event) { 
    var txtBirthDate = $('#<%= txtBirthDateCB3.ClientID %>').val(); 
    var txtNickName = $('#<%= txtNickNameCB3.ClientID %>').val(); 
    if (txtBirthDate != "") { 
     if (txtBirthDate.match(/^(?:(0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])[\/.](1920)[0-9]{2})$/)) { 
      alert("Please enter date in mm/dd/yyyy format"); 
      $('#<%= txtBirthDateCB3.ClientID %>').focus(); 
      return false; 
     } 
    } 
}); 
+0

你会得到任何错误?请记住,客户端日期时间格式也取决于浏览器文化。 – Junaid 2012-01-30 10:30:29

回答

2

我推荐你使用JavaScript日期()对象与正则表达式一起以验证日期。可以按如下方式使用this code变体:

function ValidateCustomDate(d) { 
    var match = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(d); 
    if (!match) { 
     // pattern matching failed hence the date is syntactically incorrect 
     return false; 
    } 
    var month = parseInt(match[1], 10) - 1; // months are 0-11, not 1-12 
    var day = parseInt(match[2], 10); 
    var year = parseInt(match[3], 10); 
    var date = new Date(year, month, day); 
    // now, Date() will happily accept invalid values and convert them to valid ones 
    // therefore you should compare input month/day/year with generated month/day/year 
    return date.getDate() == day && date.getMonth() == month && date.getFullYear() == year; 
} 
console.log(ValidateCustomDate("1/01/2011")); // false 
console.log(ValidateCustomDate("01/1/2011")); // false 
console.log(ValidateCustomDate("01/01/2011")); // true 
console.log(ValidateCustomDate("02/29/2011")); // false 
console.log(ValidateCustomDate("02/29/2012")); // true 
console.log(ValidateCustomDate("03/31/2011")); // true 
console.log(ValidateCustomDate("04/31/2011")); // false 
+0

我喜欢你的答案(它甚至考虑了闰年)。将从现在开始使用这个。 – 2016-01-05 18:28:23

0

如果你想使用你可以使用JavaScript的代码下面的代码片段来验证毫米/ dd/yyyy格式的日期。

txtdate由具有文本框ID

考虑下面的代码。

function isValidDate(txtdate) { 
    var txtDate = "#" + txtdate; 
    var dateString = $(txtDate).val(); 
    var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/; 
    if (!(date_regex.test(dateString))) { 
    alert("Date Must Be in mm/dd/yyyy format"); 
}} 
+0

在2015年2月29日和2015年2月30日,2015年2月31日失败 – 2015-12-22 08:38:10