I've created custom validation attribute that will be used to validate model. It allows me to specify values that are valid for specific field.
Here is my code:
public sealed class InAttribute : ValidationAttribute
{
private const string DefaultErrorMessage = "{1} is invalid value for {0}.";
private readonly int[] testArray;
private int _toTest;
public InAttribute(int[] @in) : base(DefaultErrorMessage)
{
if ([email protected]())
{
throw new ArgumentNullException("in");
}
testArray = @in;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, _toTest);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
{
return new ValidationResult("" + validationContext.DisplayName + " cant be null");
}
_toTest = Convert.ToInt32(value);
if (!testArray.Contains(_toTest))
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
return ValidationResult.Success;
}
}
Then I can use it like so:
public class RequestHelpBindingModel
{
[Required]
[In(new []{1,3,4,7},ErrorMessage = "{1} is invalid value.")]
[Display(Name = "Typ")]
public int Type { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Message { get; set; }
}
I'd like to get review on this.
My questions are:
- Is it build right?
- If there are places to optimize please let me know.