我的 MVC UI 上有一个名为“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;
}
}
但问题是,它会转到服务器来验证日期字段。我怎样才能通过客户端验证实现相同的目标。
谢谢,
-纳伦
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
Mike
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)