i going to create some validation for custom object in my app. But i have some trouble when try to create CustomValidation rule. My object has field – BirthDay – which not required but if user enter it i need to validate it on simple validation, for example user DataType validation – DataType.DateTime. When i am try to do it i have validation error – BirthDay is required. When i create custom validation and always return true i have same error. Below some lines of code:
[MetadataType(typeof(User.Metadata))]
public class User
{
#region Metadata
private class Metadata
{
[Required(ErrorMessage="Name is required")]
[StringLength(5, ErrorMessage="Max Length is 5")]
public string Name { get; set; }
[CustomValidation(typeof(User), "ValidateBirthDay", ErrorMessage="We have trouble.")]
public DateTime BirthDay { get; set; }
}
#endregion
public static bool ValidateBirthDay(object value)
{
return true;
}
public int? ID { get; set; }
public string Name { get; set; }
public DateTime BirthDay { get; set; }
}
p.s. sorry for my English =)
You need to make your propery nullable, ie
so it can have a null value and not required to be set.
Also the way you use the
CustomValidationattribute doesn’t seem right. I believe you need to create a class that derives fromValidationAttributebase class and pass its type inCustomValidationattribute’s first param.