0

I want to write a custom validator for my Web API project to check whether the input date is valid. Please find below the validator I wrote.

Validator:

   public sealed class DateValidationAttribute : ValidationAttribute
{
    public string DateString { get; set; }
    public DateValidationAttribute(string dateString)
    {
        DateString = dateString;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name, DateString);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(DateString);
        DateTime dateObject;
        if (property != null && !DateTime.TryParse(value.ToString(), out dateObject))
        {
            return new ValidationResult(
                FormatErrorMessage(validationContext.DisplayName)
            );
        }
        return null;
    }
}

Model:

public class TestModel
{
    [DateValidation("DateOfBirth", ErrorMessage = "Date of birth is not a valid date")]
    public DateTime? DateOfBirth { get; set; }
}

But if I input an invalid date, the value in the validator is coming as null (I assume its because of the model binding exception when it tries to convert value to a date). For valid dates I could see the value coming correctly. Also I can't give a null check in the validator as the model property is an optional field. I am not supposed to change the datatype of the field to "string"

Can any one help me to find an way to solve this retaining the data type DateTime?

Note: Please apologies me if there are mistakes in the question as I am a newbie to .NET technologies.

arp
  • 1,423
  • 2
  • 10
  • 11
  • What's wrong with checking for a valid model state? If what's passed in can't be bound to a `DateTime`, that's the stage that you'll get an error. – Andrew Whitaker Jun 25 '15 at 14:40
  • Even if I check the modelstate, I won't be able to get the ErrorMessage I gave to the model. I will be getting the exception message like "could not convert the value to date". I want to return the custom error message as part of validation – arp Jun 25 '15 at 14:52
  • what did your client send to API for date field? And the culture? – hazjack Jun 25 '15 at 15:35
  • any invalid date like { "DateOfBirth": "2015656-06-25", } – arp Jun 25 '15 at 15:39
  • You might want to look at [this q&a](http://stackoverflow.com/q/15377131/497356). Basically ASP.NET MVC doesn't allow you to specify error messages for invalid data types (at least it doesn't last time I tried it). You could change all of your properties to `string`s, but obviously that's not ideal either. – Andrew Whitaker Jun 25 '15 at 16:00
  • What is the point of this ValidationAttribute. It does just what the built validation does anyway. The `DefaultModelBinder` as already reset the property value to `null` by the time this is called. Is it just because you want to change the error message? If so there are other ways to handle this. –  Jun 26 '15 at 01:24
  • My requirement is just to change the error message. I was not aware that the model binder reset DateTime to null if the value is invalid initially. I would be able to achieve it(at least a generic) as per the link suggested by Andrew. Is there any other way? – arp Jun 26 '15 at 08:18
  • @arp Depending on exactly what you want, [this answer](http://stackoverflow.com/questions/6214066/how-to-change-default-validation-error-message-in-asp-net-mvc) might be what you want. Alternatively [this answer](http://stackoverflow.com/questions/19364828/how-can-i-customize-the-unobtrusive-validation-jquery-messages-in-asp-net-mvc) –  Jun 27 '15 at 02:02

0 Answers0