数据标注范围的日期(Data Annotation Ranges of Dates)

2019-07-17 15:23发布

是否有可能使用[Range]标注的日期?

就像是

[Range(typeof(DateTime), DateTime.MinValue.ToString(), DateTime.Today.ToString())]

Answer 1:

在MSDN文档说,你可以使用RangeAttribute

[Range(typeof(DateTime), "1/2/2004", "3/4/2004",
        ErrorMessage = "Value for {0} must be between {1} and {2}")]
public datetime Something { get; set;}


Answer 2:

我这样做是为了解决您的问题

 public class DateAttribute : RangeAttribute
   {
      public DateAttribute()
        : base(typeof(DateTime), DateTime.Now.AddYears(-20).ToShortDateString(),     DateTime.Now.AddYears(2).ToShortDateString()) { } 
   }


Answer 3:

jQuery验证不使用[范围(typeof运算(日期时间),“DATE1”,“日期2”]工作 - 我的MSDN文档是不正确



Answer 4:

这是另一种解决方案。

[Required(ErrorMessage = "Date Of Birth is Required")]
[DataType(DataType.Date, ErrorMessage ="Invalid Date Format")]
[Remote("IsValidDateOfBirth", "Validation", HttpMethod = "POST", ErrorMessage = "Please provide a valid date of birth.")]
[Display(Name ="Date of Birth")]
public DateTime DOB{ get; set; }

在简单地在那里创建一个名为ValidationController一个新的MVC控制器和过去的这个代码。 关于“远程”的做法的好处是,你可以利用这个框架来处理任何类型的基于自定义逻辑校验的。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;

namespace YOURNAMESPACEHERE
{
    public class ValidationController : Controller
    {
        [HttpPost]
        public JsonResult IsValidDateOfBirth(string dob)
        {
            var min = DateTime.Now.AddYears(-21);
            var max = DateTime.Now.AddYears(-110);
            var msg = string.Format("Please enter a value between {0:MM/dd/yyyy} and {1:MM/dd/yyyy}", max,min );
            try
            {
                var date = DateTime.Parse(dob);
                if(date > min || date < max)
                    return Json(msg);
                else
                    return Json(true);
            }
            catch (Exception)
            {
                return Json(msg);
            }
        }
    }
}


Answer 5:

因为当你被迫写的日期作为字符串罕见的事件(使用属性的时候),我强烈建议使用ISO-8601的符号。 这消除了任何混乱,2004年1月2日是1月2日或2月1日。

[Range(typeof(DateTime), "2004-12-01", "2004-12-31",
    ErrorMessage = "Value for {0} must be between {1} and {2}")]
public datetime Something { get; set;}


Answer 6:

我用这个方法:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
internal sealed class DateRangeAttribute : ValidationAttribute
{
    public DateTime Minimum { get; }
    public DateTime Maximum { get; }

    public DateRangeAttribute(string minimum = null, string maximum = null, string format = null)
    {
        format = format ?? @"yyyy-MM-dd'T'HH:mm:ss.FFFK"; //iso8601

        Minimum = minimum == null ? DateTime.MinValue : DateTime.ParseExact(minimum, new[] { format }, CultureInfo.InvariantCulture, DateTimeStyles.None); //0 invariantculture
        Maximum = maximum == null ? DateTime.MaxValue : DateTime.ParseExact(maximum, new[] { format }, CultureInfo.InvariantCulture, DateTimeStyles.None); //0 invariantculture

        if (Minimum > Maximum)
            throw new InvalidOperationException($"Specified max-date '{maximum}' is less than the specified min-date '{minimum}'");
    }
    //0 the sole reason for employing this custom validator instead of the mere rangevalidator is that we wanted to apply invariantculture to the parsing instead of
    //  using currentculture like the range attribute does    this is immensely important in order for us to be able to dodge nasty hiccups in production environments

    public override bool IsValid(object value)
    {
        if (value == null) //0 null
            return true;

        var s = value as string;
        if (s != null && string.IsNullOrEmpty(s)) //0 null
            return true;

        var min = (IComparable)Minimum;
        var max = (IComparable)Maximum;
        return min.CompareTo(value) <= 0 && max.CompareTo(value) >= 0;
    }
    //0 null values should be handled with the required attribute

    public override string FormatErrorMessage(string name) => string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, Minimum, Maximum);
}

并使用它像这样:

[DateRange("2004-12-01", "2004-12-2", "yyyy-M-d")]
ErrorMessage = "Value for {0} must be between {1} and {2}")]


Answer 7:

我发现有问题[Range(typeof(DateTime)]标注和将之形容为“笨拙充其量”它留下太多的机会,如果它的工作原理。

远程验证似乎是一个好办法:避免意见JavaScript和维护服务器端代码的完整性,个人从来没有像发送代码到客户端执行,如果我能避免它。

使用@StackThis答案为基础,参考到物品上在MVC3远程验证

模型

public class SomeDateModel
{
    public int MinYears = 18;
    public int MaxYears = 110;

    [Display(Name = "Date of birth", Prompt = "e.g. 01/01/1900")]
    [Remote(action: "ValidateDateBetweenYearsFromNow", controller: "Validation", areaReference: AreaReference.UseRoot, AdditionalFields = "MinYears,MaxYears", HttpMethod = "GET" ,ErrorMessage = "Subject must be over 18")]
    public DateTime? DOB { get; set; }
}

控制器-在根目录部署

namespace Controllers
{
    public class ValidationController : Controller
    {
        [HttpGet]
        [ActionName("ValidateDateBetweenYearsFromNow")]
        public JsonResult ValidateDateBetweenYearsFromNow_Get()
        {
            //This method expects 3 parameters, they're anonymously declared through the Request Querystring,
            //Ensure the order of params is:
            //[0] DateTime
            //[1] Int Minmum Years Ago e.g. for 18 years from today this would be 18
            //[2] int Maximum Years Ago e.g. for 100 years from today this would be 100
            var msg = string.Format("An error occured checking the Date field validity");
            try
            {
                int MinYears = int.Parse(Request.QueryString[1]);
                int MaxYears = int.Parse(Request.QueryString[2]);

                //Use (0 - x) to invert the positive int to a negative.
                var min = DateTime.Now.AddYears((0-MinYears));
                var max = DateTime.Now.AddYears((0-MaxYears));

                //reset the response error msg now all parsing and assignmenst succeeded.
                msg = string.Format("Please enter a value between {0:dd/MM/yyyy} and {1:dd/MM/yyyy}", max, min);
                var date = DateTime.Parse(Request.QueryString[0]);
                if (date > min || date < max)
                    //switch the return value here from "msg" to "false" as a bool to use the MODEL error message
                    return Json(msg, JsonRequestBehavior.AllowGet);
                else
                    return Json(true, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(msg, JsonRequestBehavior.AllowGet);
            }
        }
    }
}

msg变量被显示为HTML辅助的ValidationSummary或HTML辅助ValidationFor的部分(X => x.DATETIME)

视图

要注意,作为参数2和3通过了字段必须在视图中存在,为了使远程确认到值传递到所述控制器是很重要的:

    @Html.EditorFor(m => m.DOB)
    @Html.HiddenFor(m => m.MinYears)
    @Html.HiddenFor(m => m.MaxYears)
    @Html.ValidationSummary()

该模型和HTML助手将尽一切jQuery的为你工作。



文章来源: Data Annotation Ranges of Dates