【问题标题】:Retrieving the value of a condition within a custom conditional ValidationAttribute在自定义条件 ValidationAttribute 中检索条件的值
【发布时间】:2015-12-07 01:18:17
【问题描述】:

我有一个名为 [DateOfBirth] 的自定义 MVC 验证属性 - 它在模型中使用如下:

[DateOfBirth("DOBMinimumAgeValidation", 18, 100, ErrorMessage = "Please enter a valid date of birth")]
public DateTime? DateBirth { get; set; }

public Boolean DOBMinimumAgeValidation { get; set; }

“18”是最小年龄,“100”是最大年龄。

想法是,我可以将“DOBMinimumAgeValidation”属性作为参数传入,如果此参数为真,它将覆盖“最小出生日期”检查。

所以,这是我的属性代码:

public class DateOfBirthAttribute : ValidationAttribute, IClientValidatable
{
    public DateOfBirthAttribute(string conditionalProperty, int minAge, int maxAge)
    {
        _other = conditionalProperty;
        MinAge = minAge;
        MaxAge = maxAge;
    }

    public int MinAge { get; private set; }
    public int? MaxAge { get; private set; }
    private string _other { get; set; }

[...]

我的想法是,我想在 GetClientValidationRules 方法中获取“_other”的值,以便我可以覆盖它并将“MinAge”设置为 0,如果该值为 true,如下所示:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
    ModelMetadata metadata,
    ControllerContext context)
{
    //yield return new ModelClientValidationRule
    var rule = new ModelClientValidationRule
    {
        ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "dateofbirth"
    };

    if(_other.GetTheValueSomehow() == true)
        MinAge = 0;

    rule.ValidationParameters.Add("minimumage", MinAge);
    rule.ValidationParameters.Add("maximumage", MaxAge.GetValueOrDefault(999));

    yield return rule;
}

但是,我不能将“ValidationContext”对象传递给它,因为它只能从 ValidationResult 类型继承 - 所以我的问题是,如何获得“_other”的布尔值?

【问题讨论】:

  • 我假设您对 GetClientValidationRules() 方法的工作原理感到困惑。您无需在此处设置/覆盖该值 - 您需要编写 javascript 函数来添加检查客户端上 DOBMinimumAgeValidation 属性值的规则。

标签: c# asp.net-mvc validation


【解决方案1】:

我不知道这是否有帮助,但是在查看了ModelMetadata metadataControllerContext context 之后,我发现可以通过metaData.Container 访问将要验证的实际模型。剩下的就是简单的 c# 语句和反射。获取模型,检查它是否具有名称为_other 的布尔属性,如果存在此类属性,请检查其值是否为真:

var model = metadata.Container;
if (model != null)
{
    var property = model.GetType().GetProperty(_other, typeof(bool));

    if (property != null && (bool)property.GetValue(model))
    {
        MinAge = 0;
    }                
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    • 2013-08-28
    相关资源
    最近更新 更多