大于或等于MVC3今天日期的验证注解(Greater Than or Equal To Today

2019-06-25 04:39发布

有没有人见过的日期确认的MVC3数据注解,只需要一条选择的日期比当前日期等于或大于?

如果已经是一个第三方插件在这很酷了。 我已经使用了DataAnnotationsExtensions,但它并没有提供什么我要找的。

似乎没有要在这个任何引用。 所以,希望有人已经解决了这个之前,我尝试推倒重来,写我自己的自定义验证。

我试过Range ,但需要2个日期和都必须在字符串格式常量如[Range(typeof(DateTime), "1/1/2011", "1/1/2016")]但是那并不是” Ť帮助。 而DataAnnotationsExtensions Min验证只接受intdouble


更新解决

由于@BuildStarted这是我结束了和它的伟大工程的服务器端和客户端现在一侧我的脚本


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Web.Models.Validation {

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class DateMustBeEqualOrGreaterThanCurrentDateValidation : ValidationAttribute, IClientValidatable {

        private const string DefaultErrorMessage = "Date selected {0} must be on or after today";

        public DateMustBeEqualOrGreaterThanCurrentDateValidation()
            : base(DefaultErrorMessage) {
        }

        public override string FormatErrorMessage(string name) {
            return string.Format(DefaultErrorMessage, name);
        }  

        protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
            var dateEntered = (DateTime)value;
            if (dateEntered < DateTime.Today) {
                var message = FormatErrorMessage(dateEntered.ToShortDateString());
                return new ValidationResult(message);
            }
            return null;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
            var rule = new ModelClientCustomDateValidationRule(FormatErrorMessage(metadata.DisplayName));
            yield return rule;
       }
    }

    public sealed class ModelClientCustomDateValidationRule : ModelClientValidationRule {

        public ModelClientCustomDateValidationRule(string errorMessage) {
            ErrorMessage = errorMessage;
            ValidationType = "datemustbeequalorgreaterthancurrentdate";
        }
    }
}

而在我的模型

[Required]
[DateMustBeEqualOrGreaterThanCurrentDate]
public DateTime SomeDate { get; set; }

客户端脚本

/// <reference path="jquery-1.7.2.js" />

jQuery.validator.addMethod("datemustbeequalorgreaterthancurrentdate", function (value, element, param) {
    var someDate = $("#SomeDate").val();
    var today;
    var currentDate = new Date();
    var year = currentDate.getYear();
    var month = currentDate.getMonth() + 1;  // added +1 because javascript counts month from 0
    var day = currentDate.getDate();
    var hours = currentDate.getHours();
    var minutes = currentDate.getMinutes();
    var seconds = currentDate.getSeconds();

    today = month + '/' + day + '/' + year + '  ' + hours + '.' + minutes + '.' + seconds;

    if (someDate < today) {
        return false;
    }
    return true;
});

jQuery.validator.unobtrusive.adapters.addBool("datemustbeequalorgreaterthancurrentdate");

Answer 1:

创建一个自定义属性。

public class CheckDateRangeAttribute: ValidationAttribute {
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
        DateTime dt = (DateTime)value;
        if (dt >= DateTime.UtcNow) {
            return ValidationResult.Success;
        }

        return new ValidationResult(ErrorMessage ?? "Make sure your date is >= than today");
    }

}

写的代码即兴所以修复任何错误:)



Answer 2:

使用[Remote]特殊的验证,简单和容易:

您的模型:

[Remote("ValidateDateEqualOrGreater", HttpMethod="Post", 
    ErrorMessage = "Date isn't equal or greater than current date.")]
public DateTime Date { get; set; }
//other properties

你的行动:

[HttpPost]
public ActionResult ValidateDateEqualOrGreater(DateTime Date)
{
     // validate your date here and return True if validated
     if(Date >= DateTime.Now)
     {
       return Json(true);
     }
     return Json(false);    
}


Answer 3:

完成这一任务的简单方法是使用CompareValidator

下面的代码使用AjaxControlToolKit的CalendarExtender 。 下面的代码复制到您的HTML指令

<asp:TextBox ID="txtCompletionDate" runat="server" CssClass="txtNormal"></asp:TextBox>
                        <cc1:CalendarExtender ID="CalendarExtender1" TargetControlID="txtCompletionDate"
                            Format="dd/MM/yyyy" runat="server">
                        </cc1:CalendarExtender>
                        <asp:RequiredFieldValidator ID="rfvCompletionDate" runat="server" ControlToValidate="txtCompletionDate"
                            CssClass="labelError" ErrorMessage="*"></asp:RequiredFieldValidator>
                        <asp:CompareValidator ID="cvDate" runat="server" ControlToCompare="hiddenbox" ErrorMessage="*"
                            ControlToValidate="txtCompletionDate" CssClass="labelError" ToolTip="Completion  Date should be greater than or equal to Today"
                            Operator="GreaterThanEqual" Type="Date"></asp:CompareValidator>                        
                        <asp:TextBox ID="hiddenbox" runat="server" CssClass="hiddenbox">
</asp:TextBox>

添加以下行的CSS

.hiddenbox {display:none;}


文章来源: Greater Than or Equal To Today Date validation annotation in MVC3