views:

51

answers:

1

There must be a simple solution out there, I'm trying to use NHibernate Validator attributes on my DateTime properties. If the value is null (via [NotNull]), I want it to fail validation. When I submit a null value it gets converted to 1/1/0001 12:00:00 AM and NHibernate doesn't pick that up as null. I guess I could write a custom validation rule that returns false if that date is submitted, but surely there's a standard way around this?

Clarification: This is an example class,

public class ExampleClass {

  [NotNull]
  public virtual DateTime MySpecialDateProperty { get; set; }

  [NotNullOrEmpty]
  public virtual string MyString { get; set; }
}

I have NHibernate Validator setup so that in my controller, I can do:

newExampleClass.IsValid() and if it is true it'll persist in the database, if not I'll return newExampleClass.ValidationResults()

When I create a new instance of ExampleClass, the MySpecialDateProperty initializes as 1/1/0001 ... and the validator doesn't pick that up as a null value.

Edit 2: Should I set DateTime to nullable (DateTime?) which would prevent NHibernate from setting the value to the minimum DateTime?

+4  A: 

You need to use a nullable type. DateTime is initialized to DateTime.MinValue (1/1/0001). Try:

  [NotNull]
  public virtual DateTime? MySpecialDateProperty { get; set; }
Jamie Ide