我旁边有一个文本框和一个日期选择器,我使用的是asp.net,用户可以输入日期,也可以从datepicker中选择日期.
如何验证日期输入是否正确?
<script type="text/javascript"> $(document).ready(function () { $('#<%=StartDate.ClientID%>').datepicker({ showOn: 'button',buttonImage: '../images/Calendar.png',buttonImageOnly: true,onSelect: function () { },onClose: function () { $(this).focus(); } }); }); </script>
解决方法
如果您使用的是ASP.NET,则可以使用ASP.NET比较验证器[
ASP.NET Date Validator].
<asp:TextBox ID="tb" runat="server"></asp:TextBox> <asp:CompareValidator ID="cv" runat="server" ControlToValidate="tb" ErrorMessage="* Please enter a valid date!" Text="*" Operator="DataTypeCheck" Type="Date"></asp:CompareValidator>
****更新**
我使用了上面的Compare Validator执行的javascript并在其周围包装了一个自定义的jQuery Validation方法:
<script type="text/javascript"> $(document).ready(function () { $.validator.addMethod("truedate",function (value,element,params) { function GetFullYear(year,params) { var twoDigitCutoffYear = params.cutoffyear % 100; var cutoffYearCentury = params.cutoffyear - twoDigitCutoffYear; return ((year > twoDigitCutoffYear) ? (cutoffYearCentury - 100 + year) : (cutoffYearCentury + year)); } var yearFirstExp = new RegExp("^\\s*((\\d{4})|(\\d{2}))([-/]|\\. ?)(\\d{1,2})\\4(\\d{1,2})\\.?\\s*$"); try { m = value.match(yearFirstExp); var day,month,year; if (m != null && (m[2].length == 4 || params.dateorder == "ymd")) { day = m[6]; month = m[5]; year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3],10)); } else { if (params.dateorder == "ymd") { return null; } var yearLastExp = new RegExp("^\\s*(\\d{1,2})([-/]|\\. ?)(\\d{1,2})(?:\\s|\\2)((\\d{4})|(\\d{2}))(?:\\s\u0433\\.)?\\s*$"); m = value.match(yearLastExp); if (m == null) { return null; } if (params.dateorder == "mdy") { day = m[3]; month = m[1]; } else { day = m[1]; month = m[3]; } year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6],10)); } month -= 1; var date = new Date(year,day); if (year < 100) { date.setFullYear(year); } return (typeof (date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null; } catch (err) { return null; } },"Please enter an actual date."); $("#form1").validate(); $("#one").rules('add',{ truedate: { cutoffyear: '2029',dateorder: 'mdy' } }); }); </script> <input id="one" />