ASP .NET MVC 3数据注释大于LessThan的DateTime和int

use*_*898 14 validation datetime asp.net-mvc-3

我想知道在ASP.NET MVC 3表单上进行"大于"和"低于"验证的最简单方法是什么?

我使用不引人注目的JavaScript进行客户端验证.我有两个DateTime属性(StartDate和EndDate),我需要验证以确保EndDate大于StartDate.我有另一个类似的情况与另一种形式,我有一个MinValue(int)和MaxValue(int).

默认情况下是否存在此类验证?或者有人知道一篇解释如何实现它的文章吗?

Gra*_*ler 8

可以查看它为int做的Min/Max 的dataannotationsextensions

另外看看一个万无一失的验证,它包括大数字/日期时间等的比较


S.p*_*S.p 8

您可以使用自定义验证来执行此操作.

[AttributeUsage(AttributeTargets.Property, AllowMultiple=true)]
    public class DateGreaterThanAttribute : ValidationAttribute
    {
        string otherPropertyName;

        public DateGreaterThanAttribute(string otherPropertyName, string errorMessage)
            : base(errorMessage)
        {
            this.otherPropertyName = otherPropertyName;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult validationResult = ValidationResult.Success;
            try
            {
                // Using reflection we can get a reference to the other date property, in this example the project start date
                var otherPropertyInfo = validationContext.ObjectType.GetProperty(this.otherPropertyName);
                // Let's check that otherProperty is of type DateTime as we expect it to be
                if (otherPropertyInfo.PropertyType.Equals(new DateTime().GetType()))
                {
                    DateTime toValidate = (DateTime)value;
                    DateTime referenceProperty = (DateTime)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
                    // if the end date is lower than the start date, than the validationResult will be set to false and return
                    // a properly formatted error message
                    if (toValidate.CompareTo(referenceProperty) < 1)
                    {
                        validationResult = new ValidationResult(ErrorMessageString);
                    }
                }
                else
                {
                    validationResult = new ValidationResult("An error occurred while validating the property. OtherProperty is not of type DateTime");
                }
            }
            catch (Exception ex)
            {
                // Do stuff, i.e. log the exception
                // Let it go through the upper levels, something bad happened
                throw ex;
            }

            return validationResult;
        }
}
Run Code Online (Sandbox Code Playgroud)

并在模型中使用它

 [DisplayName("Start date")]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]        
    public DateTime StartDate { get; set; }

    [DisplayName("Estimated end date")]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
    [DateGreaterThan("StartDate", "End Date end date must not exceed start date")]
    public DateTime EndDate { get; set; }
Run Code Online (Sandbox Code Playgroud)

这适用于服务器端验证.对于客户端验证,您可以像GetClientValidationRules一样编写方法

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            //string errorMessage = this.FormatErrorMessage(metadata.DisplayName);
            string errorMessage = ErrorMessageString;

            // The value we set here are needed by the jQuery adapter
            ModelClientValidationRule dateGreaterThanRule = new ModelClientValidationRule();
            dateGreaterThanRule.ErrorMessage = errorMessage;
            dateGreaterThanRule.ValidationType = "dategreaterthan"; // This is the name the jQuery adapter will use
            //"otherpropertyname" is the name of the jQuery parameter for the adapter, must be LOWERCASE!
            dateGreaterThanRule.ValidationParameters.Add("otherpropertyname", otherPropertyName);

            yield return dateGreaterThanRule;
        }
Run Code Online (Sandbox Code Playgroud)

现在只是在视野中

$.validator.addMethod("dategreaterthan", function (value, element, params) {

    return Date.parse(value) > Date.parse($(params).val());
});
$.validator.unobtrusive.adapters.add("dategreaterthan", ["otherpropertyname"], function (options) {
    options.rules["dategreaterthan"] = "#" + options.params.otherpropertyname;
    options.messages["dategreaterthan"] = options.message;
});
Run Code Online (Sandbox Code Playgroud)

您可以在此链接中找到更多详细信息