我的MVC UI上的Date字段名为“startDate”,用户使用jquery日期选择器选择日期.因为我想验证所选日期不应该是过去2个月和未来2个月.
我写了下面的代码来验证日期.
public sealed class DateAttribute : DataTypeAttribute { /// <summary> /// Initializes a new instance of the <see cref="EmailAddressAttribute"/> class. /// </summary> public DateAttribute() : base(DataType.Date) { } /// <summary> /// Checks that the value of the data field is valid. /// </summary> /// <param name="value">The data field value to validate.</param> /// <returns> /// true always. /// </returns> public override bool IsValid(object value) { DateTime inputDate = Convert.ToDateTime(value,CultureInfo.CurrentCulture); if (inputDate.Date >= DateTime.Now.Date.AddMonths(-2) && inputDate.Date <= DateTime.Now.Date.AddMonths(2)) return true; return false; } }
但问题是,它用于验证日期字段的服务器.我怎么能与客户验证相同.
谢谢,
-Naren
解决方法
function IsValid(object) { var theDate = new Date(object); var pointfrom = (theDate.getFullYear() * 100) + (theDate.getMonth()); var today = new Date(); if (pointfrom > (today.getFullYear() * 100) + (today.getMonth()) + 2) return false; if (pointfrom < (today.getFullYear() * 100) + (today.getMonth()) - 2) return false; return true; }
我把年份提高了100,从而避免了跨年比较
然后在你的SPAN id =“x”onBlur =“IsValid(this.value)”> 2001-01-01
麦克风