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 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;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With