ASP.NET Core WEB API: required parameter with conditions

My property should be 7, 30 or 60.

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

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

+5
source share
1 answer

Create your own 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)}"); } 

Using:

 [RequiredNumber(7,30,60)] public int FrequenciaConsulta { get; set; } 
+7
source

Source: https://habr.com/ru/post/1274970/


All Articles