asp.net-mvc – 使用ASP.NET MVC 3.0进行日期验证

我的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

麦克风

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....