Вопрос

I've looked at so many examples, and I am doing as they all suggest, yet I keep getting an InvliadCastException with error description of:

Unable to cast object of type 'System.DateTime' to type 'System.String'

I am getting my date from a Date Of Birth Text field in an ASP.NET MVC4 application, in the following format 20/09/1986

Here is my code, I only want users above 18 years of age to be able to register.

public class AgeValidator : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        string format = "dd/MM/yyyy HH:mm:ss";
        DateTime dt;
        DateTime.TryParseExact((String)value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);


        DateTime today = DateTime.Today;
        int age = today.Year - dt.Year;
        if (dt > today.AddYears(-age)) age--;

        if (age < 18)
        {
            return false;
        }

        return true;
    }
}

My custom validation is then used like so:

[Required]
[Display(Name = "Date Of Birth")]
[AgeValidator(ErrorMessage="You need to be at least 18 years old to vote.")]
public DateTime DateOfBirth { get; set; }

How can I get the DateTime parsed correctly?

Это было полезно?

Решение

This sounds like a good place to use overloaded methods:

public override bool IsValid(DateTime value)
{
    DateTime today = DateTime.Today;
    int age = today.Year - value.Year;
    if (value > today.AddYears(-age)) age--;

    if (age < 18)
    {
        return false;
    }

    return true;
}

public override bool IsValid(string value)
{
    string format = "dd/MM/yyyy HH:mm:ss";
    DateTime dt;
    if (DateTime.TryParseExact((String)value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
    {
        return IsValid(dt);
    }
    else
    {
        return false;
    }

}

public override bool IsValid(object value)
{
    return IsValid(value.ToString());   
}

Другие советы

You can check if your object value is of type DateTime before trying to parse it to DateTime:

if(value == null)
{
  throw new ArgumentNullException("value");
}
DateTime dt ;
if(value is DateTime)
{
   dt = (DateTime)value;
}
else
{
  string format = "dd/MM/yyyy HH:mm:ss";
  DateTime.TryParseExact(value.ToString(), format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
}
//rest of your code
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top