Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core WEB API: Required parameter with conditions

My property needs to be 7, 30 or 60.

[Required]
public int FrequenciaConsulta { get; set; }

Is there something like '[Required]' that checks the values?

like image 365
Felipe Deveza Avatar asked Jan 28 '23 19:01

Felipe Deveza


1 Answers

Create a custom validation attribute.

public class RequiredNumberAttribute : ValidationAttribute, IClientModelValidator
{
    private int[] allowedNumbers;

    public RequiredNumberAttribute(params int[] numbers)
    {
         allowedNumbers = numbers;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        int number = (int)value;

        if (allowedNumbers.Contains(number))
        {
            return ValidationResult.Success;
        }

        return new ValidationResult($"Error: Number must be {string.Join(",", allowedNumbers)}");
    }

Usage would be:

[RequiredNumber(7,30,60)]
public int FrequenciaConsulta { get; set; }
like image 69
George Stocker Avatar answered Jan 31 '23 08:01

George Stocker