如何使用`String`而不是`Date`类型来验证日期?

时间:2022-12-09 19:34:36

In an Asp.net MVC app, I have inherited this problem (if it is a problem?) where one developer has used String for Date type.

在Asp.net MVC应用程序中,我继承了这个问题(如果它是一个问题?),其中一个开发人员使用String for Date类型。

In my model the property reads:

在我的模型中,该属性显示:

[Required]
[DisplayName("Registration Date")]
public string Registrationdate { get; set; }

The business requirement is that the field is not required, but if there is something in that fields then it must be a valid date.

业务要求是该字段不是必需的,但如果该字段中存在某些内容,则它必须是有效日期。

How would you implement this requirement, without changing the data type?

如何在不更改数据类型的情况下实现此要求?

4 个解决方案

#1


8  

It looks like you're using System.ComponentModel.DataAnnotations. The best way to do this using this library would be to create a new attribute to validate date strings and apply it to the property. Here's some code for you to start with:

看起来你正在使用System.ComponentModel.DataAnnotations。使用此库执行此操作的最佳方法是创建新属性以验证日期字符串并将其应用于属性。这里有一些代码供您开始:

[AttributeUsage(AttributeTargets.Property, Inherited = true)]
class DateAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var dateString = value as string;
        if (string.IsNullOrWhiteSpace(dateString))
        {
            return true; // Not our problem
        }
        DateTime result;
        var success = DateTime.TryParse(dateString, out result);
        return success;
    }

You'll probably want to expand on this code depending on what kind of strings you're expecting from the client. Also, this won't give you any client-side validation.

您可能希望扩展此代码,具体取决于您希望客户端使用哪种字符串。此外,这不会给您任何客户端验证。

#2


7  

public string Registrationdate { 
    get; 
    set {
        DateTime date;
        var isDate = DateTime.TryParse(value, out date);
        if (isDate) { 
            _registrationDate = value; 
        }
        else {
          // Throw exception
        }
    }
}

#3


1  

(sort of) pseudocode:

(有点)伪代码:

if (Registrationdate is not empty)
{
    RegistrationDateTime = new DateTime(Registrationdate);

    if (RegistrationDateTime is not valid DateTime)
        fail validation;
}

#4


0  

How about a regular expression? Data Annotations has a regex attribute. Now you'd have to fix on a format, say ISO (yyyy/mm/dd) which may not meet your requirements.

正则表达怎么样? Data Annotations具有正则表达式属性。现在你必须修改一个格式,比如ISO(yyyy / mm / dd)可能不符合你的要求。

Another alternative may be to create your own annotation.

另一种选择可能是创建自己的注释。

Yet another solution could to use a nullable datetime (DateTime?). I'm not sure how that would be handled though, so some trial and error would be needed. It does however only need the addition of one ? so could be relatively easy to try.

另一种解决方案可以使用可以为空的日期时间(DateTime?)。我不确定如何处理,所以需要一些反复试验。但它只需要添加一个?所以可能相对容易尝试。

Simon

#1


8  

It looks like you're using System.ComponentModel.DataAnnotations. The best way to do this using this library would be to create a new attribute to validate date strings and apply it to the property. Here's some code for you to start with:

看起来你正在使用System.ComponentModel.DataAnnotations。使用此库执行此操作的最佳方法是创建新属性以验证日期字符串并将其应用于属性。这里有一些代码供您开始:

[AttributeUsage(AttributeTargets.Property, Inherited = true)]
class DateAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var dateString = value as string;
        if (string.IsNullOrWhiteSpace(dateString))
        {
            return true; // Not our problem
        }
        DateTime result;
        var success = DateTime.TryParse(dateString, out result);
        return success;
    }

You'll probably want to expand on this code depending on what kind of strings you're expecting from the client. Also, this won't give you any client-side validation.

您可能希望扩展此代码,具体取决于您希望客户端使用哪种字符串。此外,这不会给您任何客户端验证。

#2


7  

public string Registrationdate { 
    get; 
    set {
        DateTime date;
        var isDate = DateTime.TryParse(value, out date);
        if (isDate) { 
            _registrationDate = value; 
        }
        else {
          // Throw exception
        }
    }
}

#3


1  

(sort of) pseudocode:

(有点)伪代码:

if (Registrationdate is not empty)
{
    RegistrationDateTime = new DateTime(Registrationdate);

    if (RegistrationDateTime is not valid DateTime)
        fail validation;
}

#4


0  

How about a regular expression? Data Annotations has a regex attribute. Now you'd have to fix on a format, say ISO (yyyy/mm/dd) which may not meet your requirements.

正则表达怎么样? Data Annotations具有正则表达式属性。现在你必须修改一个格式,比如ISO(yyyy / mm / dd)可能不符合你的要求。

Another alternative may be to create your own annotation.

另一种选择可能是创建自己的注释。

Yet another solution could to use a nullable datetime (DateTime?). I'm not sure how that would be handled though, so some trial and error would be needed. It does however only need the addition of one ? so could be relatively easy to try.

另一种解决方案可以使用可以为空的日期时间(DateTime?)。我不确定如何处理,所以需要一些反复试验。但它只需要添加一个?所以可能相对容易尝试。

Simon