使用ASP.NET MVC 3.0日期验证 [英] Date Validation using ASP.NET MVC 3.0
问题描述
我已经在我的命名为的startDateMVC UI日期字段,用户使用jQuery日期选择器选择日期。因为我想,以验证选择的日期不应该在2个月过去2个月的未来。
我已经写了下面code,用于验证的日期。
公共密封类DateAttribute:DataTypeAttribute
{
///<总结>
///初始化℃的新的实例;参见CREF =EmailAddressAttribute/>类。
///< /总结>
公共DateAttribute():基地(DataType.Date)
{
} ///<总结>
///检查该数据字段的值是有效的。
///< /总结>
///< PARAM NAME =值>该数据字段的值来验证< /参数>
///<退货和GT;
///真的总是如此。
///< /回报>
公众覆盖BOOL的IsValid(对象的值)
{
日期时间inputDate = Convert.ToDateTime(值,CultureInfo.CurrentCulture); 如果(inputDate.Date&GT = DateTime.Now.Date.AddMonths(-2)及&放大器; inputDate.Date&下; = DateTime.Now.Date.AddMonths(2))
返回true; 返回false;
}
}
但问题是,它进入服务器用于验证日期域。我怎么能achive用相同的客户端验证。
谢谢,
-Naren
函数的IsValid(对象){
VAR theDate =新的日期(对象);
变种pointfrom =(theDate.getFullYear()* 100)+(theDate.getMonth());
VAR今天=新的Date();
如果(pointfrom>(today.getFullYear()* 100)+(today.getMonth())+ 2)返回false;
如果(pointfrom≤(today.getFullYear()* 100)+(today.getMonth()) - 2)返回false;
返回true;
}
我的因素同比增长100,从而避免跨年度比较 P>
然后在您的SPAN ID =X的onblur =的IsValid(THIS.VALUE)> 2001-01-01
迈克
I've Date field on my MVC UI named "startDate", the user selects date using jquery date picker. As i wanted to validate that selected date should not be 2 months past and 2 months future.
I've wrote the below code for validating the date.
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;
}
}
But the issue is, it goes to server for validating the date field. how can i achive same with client validation.
Thanks, -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;
}
I factor the year up by 100, thereby avoiding cross year comparison
Then on your SPAN id="x" onBlur="IsValid(this.value)">2001-01-01
Mike
这篇关于使用ASP.NET MVC 3.0日期验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!