0

I have a basic form which has a date field and I want to validate it inside the IValidatableObject. The type of the field is mapped to a DateTime property so if someone types in 26/15/2011, how do you pick that up in the Validate method? Strictly speaking its almost like validating a DateTime object with a DateTime which doesn't make sense. Any ideas on how to get around this or how to detect that its the wrong date?

MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
fes
  • 2,465
  • 11
  • 40
  • 56

1 Answers1

1

Implement IValidatableObject on your method and make the validation for this field

e.g.

public class YourModel : IValidatableObject
{
    public YourModel()
    {
    }

    [Required(ErrorMessage = "date  is required")]
    public string Date { set; get; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        DateTime result;
        bool parseDone = DateTime.TryParse(Date, out result);
        if (!parseDone)
        {
             yield return new ValidationResult(Date + "is invalid", new[] { "Date" });
        }            
    }
}

I suggest to use jquery validate and jqueryUI calendar for client side

Hope it helps

k-dev
  • 1,657
  • 19
  • 30
  • Hi I don't want to make a Date a string like you have. I think I've worked it out, if the date is invalid it seems to set itself to DateTime.MinValue so that's all I need to check. – fes May 26 '11 at 22:03