将参数传递给 MVC 中的自定义验证属性 ASP.NET



我正在使用 ASP.NET MVC,我想创建一个自定义验证属性来验证从文本输入引用的StartTimeEndTime

我试过:

型:

public class MyModel
{
public bool GoldTime { get; set; }
[TimeValidation(@"^d{1,2}:d{1,2}$", GoldTime, ErrorMessage = "Start time is invalid.")]
public string StartTime { get; set; }
[TimeValidation(@"^d{1,2}:d{1,2}$", GoldTime, ErrorMessage = "End time is invalid.")]
public string EndTime { get; set; }
}

验证属性:

public class TimeValidationAttribute : ValidationAttribute
{
private readonly string _pattern;
private readonly bool _useGoldTime;
public TimeValidationAttribute(string pattern, bool useGoldTime)
{
_pattern = pattern;
_useGoldTime = useGoldTime;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_useGoldTime)
{
var regex = new Regex(_pattern);
if (!regex.IsMatch(value.ToString()))
{
return new ValidationResult(ErrorMessage);
}
}
return ValidationResult.Success;
}
}

但是我收到此错误消息:

非静态字段、方法或 属性 'MyModel.GoldTime'

然后,我再次尝试将GoldTime(在模型中(更改为true,错误消息将消失。

所以,我的问题是:如何将参数GoldTime传递给属性构造函数?我需要使用GoldTime作为密钥来验证StartTimeEndTime的值。

谢谢!

它抱怨在属性定义中使用模型属性。 相反,在您的自定义属性中,您可以使用 ValidationContext 类上的属性来获取基础模型,我认为通过validationContext.ObjectInstance.

显然,您不想对模型类型进行硬编码,但可以使用反射:

bool goldTime;
var prop = validationContext.ObjectInstance.GetType().GetProperty("GoldTime");
if (prop != null)
goldTime = (bool)prop.GetValue(validationContext.ObjectInstance, null);

或者,为模型定义一个接口:

public interface ITimeModel
{
bool GoldTime { get; set; }
}

并寻找:

bool goldTime;
if (validationContext.ObjectInstance is ITimeModel)
goldTime = ((ITimeModel)validationContext.ObjectInstance).GoldTime;

最新更新