0

I'm trying to validate a field in a model which should contain one of the options from a list. I could do this through a normal method, but I ideally wanted to utilise a ValidationAttribute so it could be run on ModelState.IsValid.

As an example the client-side could send one of the following items:

"00",
"01",
"02",
"03"

On my server-side, we have record of the following items in the dropdown:

return Dropdown[] {
    new Dropdown() 
    {
        Title = "a value",
        Value = "00"
    },
    new Dropdown()
    {
        Title = "another value",
        Value = "01"
    }
    ...
}

Then as an example, the model we receive could be:

public class MyData 
{
    [Exists]
    public string Selected { get; set; }
}

What I'm trying to achieve, is taking the list of expected dropdown items, selecting the "Value" from the object only, and checking that one of those values is present in the "Selected" field.

The below is not working, C# won't let me pass in Dropdown[] into the validation class. Similarly, I am unable to pass in a string[] that is computed at runtime.

public sealed class ExistsAttribute : ValidationAttribute
{
    private readonly string[] AllowedValues;
    public ExistsAttribute(Dropdown[] allowedValues)
    {
        AllowedValues = allowedValues.Select(c => c.Value).ToArray();
    }

    public override bool IsValid(object value)
    {
        string converted = value.ToString();
        if (!string.IsNullOrWhiteSpace(converted))
        {
            if (AllowedValues.Contains(converted))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return true;
        }
    }
}

Does anyone know how to achieve something like this?

UncountedBrute
  • 484
  • 1
  • 7
  • 25
  • Side note: your ``IsValid()`` method is just a complicated way to write ``return string.IsNullOrWhiteSpace(converted) || AllowedValues.Contains(converted);`` – dumetrulo Feb 12 '21 at 19:35
  • Yeah I tend to write code in a larger format first, then trim down once I have the process ironed out. – UncountedBrute Feb 15 '21 at 08:46

0 Answers0