Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing custom parameters to ValidationAttribute

Tags:

I built a custom ValidationAttribute so I can validate unique email addresses in my system. However, I'd like to pass in a custom parameter somehow to add more logic to my validation.

public class UniqueEmailAttribute : ValidationAttribute {     public override bool IsValid(object value)     {         //I need the original value here so I won't validate if it hasn't changed.         return value != null && Validation.IsEmailUnique(value.ToString());     } } 
like image 358
Mike Cole Avatar asked Feb 12 '13 15:02

Mike Cole


1 Answers

Like this?

public class StringLengthValidatorNullable : ValidationAttribute {     public int MinStringLength { get; set; }     public int MaxStringLength { get; set; }      public override bool IsValid(object value)     {         if (value == null)         {             return false;         }         var length = value.ToString().Length;          if (length < MinStringLength || length >= MaxStringLength)         {             return false;         }         return true;     } } 

Use:

[StringLengthValidatorNullable(MinStringLength = 1, MaxStringLength = 16)] public string Name {get; set;} 
like image 81
Oliver Avatar answered Oct 19 '22 18:10

Oliver