ValidationAttribute for Specific Values Only

50 Views Asked by At

Is there ValidationAttribute in .net for closed set of values?

For instance in the code below, only "a", "b" and "c" are the valid values for StringType property, and 1, 10, 100 are the only allowed values for IntType

  public record RequestModel
  {
     [StringOptions("a", "b", "c")
     public string StringType{get; init;}


     [IntOptions(1, 10, 100)
     public string IntType{get; init;}
  }

10x.

1

There are 1 best solutions below

0
Suryateja KONDLA On

For Older versions there is no built-in ValidationAttribute that allows a property to have a closed set of specific values directly in the way you're describing with StringOptions or IntOptions

Create a Ccustom validation attributes

public class StringOptionsAttribute : ValidationAttribute
{
    private readonly string[] _options;

    public StringOptionsAttribute(params string[] options)
    {
        _options = options;
    }

    public override bool IsValid(object value)
    {
        if (value == null) return true;  

        string stringValue = value as string;
        return _options.Contains(stringValue);
    }
}

public class IntOptionsAttribute : ValidationAttribute
{
    private readonly int[] _options;

    public IntOptionsAttribute(params int[] options)
    {
        _options = options;
    }

    public override bool IsValid(object value)
    {
        if (value == null) return true;  

        if (value is int intValue)
        {
            return _options.Contains(intValue);
        }
        return false;
    }
}

public record RequestModel
{
    [StringOptions("a", "b", "c")]
    public string StringType { get; init; }

    [IntOptions(1, 10, 100)]
    public int IntType { get; init; }
}

For better validation rules use Fluent Validator it provides lot of features.