Tag Archives: data

DataAnnotations Custom Validation

17 Nov

I am putting this here because it took me way to long to find this information today.

Reference Links for this information:
[custom-validation-attributes]
[msdn]

To create a custom DataAnnotations validation attribute inherit from ValidationAttribute and implement IsValid.

public class CustomAttributeName : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        bool validFlag = false;
        // perform validation here
        if (validFlag)
            return true;
        else
            return false;
    }
}

In the Model Validation Meta class use the custom validation attribute like this.

[MetadataType(typeof(EntityMetadata))]
public partial class Entity
{
    public class EntityMetadata
    {
        [CustomAttributeName(ErrorMessage=" [Required] ")]
        public object FieldName { get; set; }
    }
}