Creating a custom validation attribute C# with Example



Creating a custom validation attribute C# with Example

Custom validation attributes can be created by deriving from the ValidationAttribute base class, then overriding 
virtual methods as needed. 
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] 
public class NotABananaAttribute : ValidationAttribute 
{ 
public override bool IsValid(object value) 
{ 
var inputValue = value as string; 
var isValid = true; 
if (!string.IsNullOrEmpty(inputValue)) 
{ 
isValid = inputValue.ToUpperInvariant() != "BANANA"; 
} 
return isValid; 
} 
} 
This attribute can then be used like this: 
public class Model 
 

{ 
[NotABanana(ErrorMessage = "Bananas are not allowed.")] 
public string FavoriteFruit { get; set; } 
} 

0 Comment's

Comment Form