gpt4 book ai didi

c# - 如果字段为空或错误,则日期时间的 RequiredAttribute

转载 作者:行者123 更新时间:2023-12-05 08:19:03 26 4
gpt4 key购买 nike

RequiredAttribute 适用于 string 但不适用于 DateTime。例如:

    [Required]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Name { get; set; }

[Required]
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MMM-yyyy}", ConvertEmptyStringToNull = false)]
public DateTime Birthdate { get; set; }

如果 Name 为空,则验证显示错误,但如果 Birthdate 为空,则什么也不会发生。我看了看:

ASP MVC 5 Client Validation for Range of Datetimes

MVC Model Range Validator?

但仍然不适用于 DateTime

最佳答案

DateTime是一个结构体,结构体是“值类型”,不是“引用类型”,所以它们的默认值不是null,对于DateTime1/1/0001 12:00:00 AMint 的默认值为 0

string 类型是一种“引用类型”,所有引用类型的默认值为null

因此,如果您想检查值类型是否为 null,您应该将其创建为 Nullable

像这样:

public DateTime? Birthdate { get; set; }

或者

public Nullable<DateTime> Birthdate { get; set; }

关于c# - 如果字段为空或错误,则日期时间的 RequiredAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35893680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com