Arno 2501
Arno 2501

Reputation: 9397

Validation error when no mandatory data supplied

I have a model with a custom DateRange Validation Attribute

public class Step1ViewModel
{
    [DataType(DataType.Date)]
    [DateRange(ErrorMessage="Date must be between blabla")]
    public DateTime? BirthDate1 { get; set; }
}

When I display this model with a View it raises the error from the custom Validation Attribute even when I submit without supplying a date. I did not tag this property with [Required] and the property is nullable (DateTime?). I don't understand this behaviour.

I would like to be able to NOT supply a date without raising the error.

Here is the custom Validation Attribute :

 public class DateRangeAttribute : ValidationAttribute
 {
        public DateTime FirstDateYears { get; set; }
        public DateTime SecondDateYears { get; set; }

        public DateRangeAttribute()
        {
            FirstDateYears = Convert.ToDateTime("1801-01-01");
            SecondDateYears = Convert.ToDateTime("2101-01-01");
        }

        public override bool IsValid(object value)
        {
            DateTime date = Convert.ToDateTime(value); // assuming it's in a parsable string format

            if (date > FirstDateYears && date < SecondDateYears)
                return true;

            return false;
        }
    }

Upvotes: 2

Views: 86

Answers (1)

Logard
Logard

Reputation: 1513

Try this:

public override bool IsValid(object value)
{
    if(value == null){
        return true;
    }
    DateTime date = Convert.ToDateTime(value); 

    if (date > FirstDateYears && date < SecondDateYears)
        return true;

    return false;
}

Im think you need to be specific about what to do with null values if you want a custom validator. This should tell the validator that no value is valid.

Hope this helps!

Upvotes: 2

Related Questions