Tag Archives: c# mvc validation asp.net
Custom Validation Attributes
In my last post I showed you how to use Validation attributes on your model for validation. Today I will show how you can create your own attributes that can provide custom validation for you.
To accomplish this we need to inherit from ValidationAttribute. We’ll create an attribute today that will only allow a "Yes" or "No" value to be entered. A pretty bad example however it will still suffice.
public class TwoValueAttribute : ValidationAttribute { private string str1 { get; set; } private string str2 { get; set; } public TwoValueAttribute(string str1, string str2) { this.str1 = str1; this.str2 = str2; } public override bool IsValid(object value) { if (value.ToString() == str1 || value.ToString() == str2) return true; else return false; } public override string FormatErrorMessage(string name) { return string.Format(CultureInfo.CurrentCulture, base.ErrorMessageString, name, this.str1, this.str2); } } |
All the validation logic takes place in the IsValid function. You can override the FormatErrorMessage function so that you can supply a custom error message for each instance that you want to validate if you so wish.
I’ll show you what I mean.
public class MyOrder : CustomValidation { [TwoValue("Yes","No", ErrorMessage="Only the values '{1}' and '{1}' are possible" + " for the {0} field")] public string Value1 { get; set; } [TwoValue("Yes", "No")] public string Value2 { get; set; } } |
Value2 in the above case will give you the default error message if the value is not "Yes" or "No". However if Value1 is not "Yes" or "No" then the error message supplied will be used and the tokens replaced by the value entered, and the two values used for validation.
And that’s it. Pretty simple really.
Cheers,
Adam