【问题标题】:C# model validation shows valid Date range as invalidC# 模型验证将有效日期范围显示为无效
【发布时间】:2021-09-21 19:04:46
【问题描述】:

我的模型有一个这样的日期字段:

[Display(Name = "Date of Birth")]
[Required(AllowEmptyStrings = false, ErrorMessage = "This field is required.")]
[Range(typeof(DateTime), "1/1/2000", "1/1/2010", ErrorMessage = "Date is out of Range")]
public string DOB { get; set; }

在我看来,我有这个字段:

@Html.TextBoxFor(m => m.DOB, new { @class = "form-control", @id = "dob", type = "Date" })
@Html.ValidationMessageFor(m => m.DOB)

日期始终无效,即使日期在范围内。


【问题讨论】:

  • 尝试指定格式 DisplayFormat(DataFormatString = "{0:mm-dd-yyyy}", ApplyFormatInEditMode = true)]
  • @Nonik 感谢您的回复。使用 DisplayFormat 时得到相同的结果
  • 您 DOB 是字符串类型,但您尝试验证 DateTime 类型。您可以制作自定义验证器或将字符串转换为 DateTime 并返回。

标签: c# asp.net-mvc validation data-annotations


【解决方案1】:

您是否尝试过使用 Datetime 属性进行验证? 类似的东西:

[Display(Name = "Date of Birth")]
[Required(ErrorMessage = "This field is required.")]
[Range(typeof(DateTime), "1/1/2000", "1/1/2010", ErrorMessage = "Date is out of Range")]
[DataType(DataType.Date)]
public DateTime DOB { get; set; } 

【讨论】:

【解决方案2】:

您的 DOB 是字符串类型,但您尝试验证 DateTime 类型。您可以制作自定义验证器,也可以尝试制作类似这样的工作

public string DOB 
{
get {  return DOBDateTime.ToString("dd/MM/yyyy HH:mm:ss"); }
set  { DobDateTime= DateTime.Parse(value);  }
}


[NotMapped]

[Display(Name = "Date of Birth")]
[Required(ErrorMessage = "This field is required.")]
[Range(typeof(DateTime), "1/1/2000", "1/1/2010", ErrorMessage = "Date is out of Range")]
[DataType(DataType.Date)]
public DateTime DOBDateTime { get; set; } 

在这种情况下,您必须仅将 DOBDateTime 用于用户界面

【讨论】:

    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    相关资源
    最近更新 更多