我的财产必须是7,30或60。
[Required]
public int FrequenciaConsulta { get; set; }
是否有类似“[必需]”的内容来检查值?
答案 0 :(得分:8)
创建自定义验证属性。
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)}");
}
用法是:
[RequiredNumber(7,30,60)]
public int FrequenciaConsulta { get; set; }