views:

26

answers:

1

Related to this question

I have created my own DateValidationAttibute to make sure a string is in a valid date format (e.g., MM/DD/YYYY)

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class DateValidationAttribute : DataTypeAttribute
{
    public DateValidationAttribute() : base(DataType.Date){}

    //MM/DD/YYYY, MM-DD-YYYY
    public override bool IsValid(object value)
    {
        //validation logic
    }
}

I am trying to test this attribute with this code

    [Test]
    public void Test()
    {
        var invalidObject = new TestValidation {DateField = "bah"};
        var validationContext = new ValidationContext(invalidObject, null, null);
        var validationResults = new System.Collections.Generic.List<ValidationResult>();

        bool result = Validator.TryValidateObject(invalidObject, validationContext, validationResults);

        Assert.IsFalse(result);
        Assert.AreEqual(1, validationResults.Count);
    }

    private class TestValidation
    {
        [DateValidation(ErrorMessage = "Invalid Date!")]
        public string DateField { get; set; }
    }

Unfortunately this isn't working. I put a breakpoint at the DateValidationAttribute constructor, and the IsValid method. It definitely hits the constructor, but never hits the IsValid method. Any ideas?

A: 

I've never tried creating ValidationAttributes using the DataTypeAttribute class and I'm not sure if this is wrong but extending the ValidationAttribute class has always worked for me.

"DataTypeAttribute doesn't do any validation by default. But it does influence templates regarding how the data is presented." taken from this question

Example :

[AttributeUsage(AttributeTargets.Field,  AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class MyCustomAttribute : ValidationAttribute
{
  public MyCustomAttribute()
    : base("Custom Error Message: {0}")
  {
  }

  public override bool IsValid(object value)
  {
    return true;
  }
}
Manaf Abu.Rous
@Manaf, changing my example to extend from ValidationAttribute doesn't help. Keep in mind that DataTypeAttribute already extends from ValidationAttribute.
manu08