MVC模式范围验证?

编程入门 行业动态 更新时间:2024-10-25 16:25:41
本文介绍了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模式范围验证?

本文发布于:2023-11-16 07:35:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1602276.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式   MVC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!