atashbahar.com

thoughts, ideas and ...

Contains in array list validation attribute for ASP.NET MVC

Following custom validation attribute checks if the posted value is one of the values available in the list of valida values for that attribute.

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;

namespace MyWebApplication.Models
{
    public sealed class ContainsAttribute : ValidationAttribute
    {
        private readonly IEnumerable<string> _values;

        public ContainsAttribute(string[] values)
        {
            _values = values;
        }

        public ContainsAttribute(int[] values)
        {
            _values = values.Select(x => x.ToString());
        }

        public ContainsAttribute(double[] values)
        {
            _values = values.Select(x => x.ToString(CultureInfo.InvariantCulture));
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
                return ValidationResult.Success;

            if (_values != null && !_values.Contains(value))
            {
                var valuesString = string.Join(", ", _values.Select(x => $"'{x}'"));
                var message = $"Provided value for {validationContext.MemberName} property is not valid. Valid values are {valuesString}.";
                return new ValidationResult(message);
            }

            return ValidationResult.Success;
        }
    }
}

You can use it like this:

[Contains(new[] { "first value", "second value", "third value" })]
public string MyValue { get; set; }