This project is read-only.

Validate method not working for DateTime value

Nov 29, 2012 at 3:40 PM

I wonder if this is a bug. 

Basically I am trying to validate a DateTime Property called 'DateOfReceipt'. See the sample code below. The framework seems to me doesn't prompt me error if I entered invalid value. I tested on an integer type property, it worked. 

So let me make me thinks this could be a bug for DateTime value. Could you please confirm?

 

   public virtual Nullable<System.DateTime> DateOfReceipt { get; set; }

 

 public string ValidateDateOfReceipt(DateTime dateOfReceipt)  

{           

if (DateTime.Compare(dateOfReceipt, DateTime.Today) > 0)           

{               

return "*Date of Receipt should not be in the future*";           

}           

return null;       

}

Nov 29, 2012 at 3:43 PM
I suspect it's a mismatch in the datatype of the validate... the property is a DateTime?, but the parameter to the validate is just DateTime.

By the way, you could use a ternary for the return: return x? "foo": "bar; Just a pet peeve of mine.

Dan

Nov 29, 2012 at 6:16 PM

Thanks very much Dan, you are right to say that there is a mismatch in datatype of validate method. After I corrected that, the validation method did get called. 

However, when the validate method is called, the dateOfReceipt value passed into the method is not the one user just entered. It's actually the previous one. For instance, if user enters 24/12/2012, this value is not passed, instead it's the previous value gets passed. This seems to me it's a bug. 

 

Nov 29, 2012 at 6:24 PM
I'll leave that for Stef to check, if that's ok.

Nov 30, 2012 at 7:41 AM

I'm wondering if that might be a browser issue, Xiao?  Please confirm which browser and version you are using, and, if possible, see if you are getting the same behaviour on a different browser.

 

(BTW, in addition to Dan's comment about ternary operators, please note that Naked Objects add some  very useful extension methods to DateTime, so I think you can write e.g:

 

return dateOfReceipt.IsAfterToday() ? "msg", null;

or you can use the Range attribute e.g.

[Range(-30, 0)]
public virtual Nullable<System.DateTime> DateOfReceipt { get; set; }

should permit only days in the range 30 days ago to today.

 


Nov 30, 2012 at 11:05 AM

Thanks Richard, I rebooted my machine this morning and tested on both IE 8 and Chrome. They both worked fine. I should have done that yesterday. :-)

Also tested the extension method and Range attribute, they both work well as well. Thanks again for your answers.