本文介绍了MVC模式范围验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我wnat验证日期时间,我的code是:

i wnat to validate the datetime, My Code is:

    [Range(typeof(DateTime),
     DateTime.Now.AddYears(-65).ToShortDateString(),
     DateTime.Now.AddYears(-18).ToShortDateString(),
     ErrorMessage = "Value for {0} must be between {1} and {2}")]
    public DateTime Birthday { get; set; }

但我得到的错误:

but i get the error:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

请帮帮我吗?

推荐答案

这意味着不能在一段时间后确定的范围属性的值,它在编译时确定。 DateTime.Now不是一个常数,它的变化取决于code运行时。

This means the values for the Range attribute can't be determined at some later time, it has to be determined at compile time. DateTime.Now isn't a constant, it changes depending on when the code runs.

你想要的是一个自定义的验证DataAnnotation。下面是如何建立一个的例子:

What you want is a custom DataAnnotation validator. Here's an example of how to build one:

How创建自定义数据校验注释

把你的日期验证逻辑的IsValid()

Put your date validation logic in IsValid()

下面是一个实现。我也是用DateTime.Subtract(),而不是消极年。

Here's an implementation. I also am using DateTime.Subtract() as opposed to negative years.

public class DateRangeAttribute : ValidationAttribute
{
    public int FirstDateYears { get; set; }
    public int SecondDateYears { get; set; }

    public DateRangeAttribute()
    {
        FirstDateYears = 65;
        SecondDateYears = 18;
    }

    public override bool IsValid(object value)
    {
        DateTime date = DateTime.Parse(value); // assuming it's in a parsable string format

        if (date >= DateTime.Now.AddYears(-FirstDateYears)) && date <= DateTime.Now.AddYears(-SecondDateYears)))
        {
            return true;
        }

        return false;
}

}

用法为:

[DateRange(ErrorMessage = "Must be between 18 and 65 years ago")]
public DateTime Birthday { get; set; }

这也是通用的,因此可以为指定年新范围值。

It's also generic so you can specify new range values for the years.

[DateRange(FirstDateYears = 20, SecondDateYears = 10, ErrorMessage = "Must be between 10 and 20 years ago")]
public DateTime Birthday { get; set; }

这篇关于MVC模式范围验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 08:03