views:

480

answers:

1

Hello SO,

I'm currently working in an MVC 2 app which has to have everything localized in n-languages (currently 2, none of them english btw). I validate my model classes with DataAnnotations but when I wanted to validate a DateTime field found out that the DataTypeAttribute returns always true, no matter it was a valid date or not (that's because when I enter a random string "foo", the IsValid() method checks against "01/01/0001 ", dont know why).

Decided to write my own validator extending ValidationAtribute class:

public class DateTimeAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        DateTime result;
        if (value.ToString().Equals("01/01/0001 0:00:00"))
        {
                return false;
        }
        return DateTime.TryParse(value.ToString(), out result);
    }
}

Now it checks OK when is valid and when it's not, but my problem starts when I try to localize it:

[Required(ErrorMessageResourceType = typeof(MSG), ErrorMessageResourceName = "INS_DATA_Required")]
[CustomValidation.DateTime(ErrorMessageResourceType = typeof(MSG), ErrorMessageResourceName = "INS_DATA_DataType")]
public DateTime INS_DATA { get; set; }

If I put nothing in the field I get a localized MSG (MSG being my resource class) for the key=INS_DATA_Required but if I put a bad-formatted date I get the "The value 'foo' is not valid for INS_DATA" default message and not the localized MSG.

What am I misssing?

A: 

It could be that your ToString() is using a 'localized' format so your hard coded string will not match. try replacing your "if" condition with:

if((DateTime)value == DateTime.MinValue)
Myster
That "if" works fine as is, btw yours is more polite. My question refered more to the fact that, even though I'm specifying both ErrorMessageResourceType and ErrorMessageResourceName in the Model field I still get the default error message in english "The value 'blah' is not valid for INS_DATA" which isn't what I hard-coded in my resource file.
Gabe G
Oh right. I'm not sure, *lame answer follows:* it sounds like it can't find the resource :-]
Myster