试图了解如何将变量传递给CustomValidation?

时间:2016-08-10 12:47:17

标签: c# asp.net-mvc asp.net-mvc-5

我正在尝试了解如何将数据传递给我创建的自定义验证。

我有这个模型。

public class MyModel
{
    [Required(ErrorMessage="Please enter a Start Date")]  
    public DateTime StartDate { get; set; }

    [Required(ErrorMessage="Please enter an End Date")]
    [CustomValidation(typeof(DateCompareValidation), "ValidateDates")]
    public DateTime EndDate { get; set; }
}

这是我的验证员。

public class DateCompareValidation
{
    public static ValidationResult ValidateDates(object value, ValidationContext context)
    {
        return new ValidationResult("You are wrong");
    }
}


我第一次使用公共静态ValidationResult ValidateDates()并且它出错了

"..must match the expected signature: public static ValidationResult ValidateDates(object value, ValidationContext context)." 

所以我添加了必要的参数。

现在调试类我看到变量“value”有我的结束日期。 我不太明白它是如何知道它需要什么参数的。
另外我想知道如何传递开始日期或MyModel类,以便我可以处理验证逻辑?

3 个答案:

答案 0 :(得分:0)

这可能会对你有帮助。

class CustomLengthValidatorAttribute : ValidationAttribute
{
    /// <summary>
    /// Initializes a new instance of the <see cref="CustomLengthValidatorAttribute" /> class.
    /// </summary>
    /// <param name="maxLength">The maximum length.</param>
    public CustomLengthValidatorAttribute(int maxLength)
    {
        this.MaxLength = maxLength;
    }

    /// <summary>
    /// Gets the minimum length.
    /// </summary>
    /// <value>
    /// The minimum length.
    /// </value>
    public int MaxLength { get; private set; }

    /// <summary>
    /// Validates the specified value with respect to the current validation attribute.
    /// </summary>
    /// <param name="value">The value to validate.</param>
    /// <param name="validationContext">The context information about the validation operation.</param>
    /// <returns>
    /// An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult" /> class.
    /// </returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string fieldName = validationContext.MemberName;
        if (Convert.ToString(value).Trim().Length > this.MaxLength)
        {
            return new ValidationResult(this.ErrorMessage = fieldName + " should not be longer than " + this.MaxLength + " character");
        }

        return ValidationResult.Success;
    }
}

答案 1 :(得分:0)

虽然它没有仔细回答你的问题,但我建议你看看FluentValidation。 它可以用fluent语法接口(使用用户定义的验证器类)完全替换内置的基于ASP.NET MVC属性的验证。

例如,如果您想验证StartDate是否在EndDate之前,则可能如下所示:

// validator class for your view model
public class MyModelValidator : AbstractValidator<MyModel>
{
    public MyModelValidator()
    {
        RuleFor(m => m.EndDate).NotNull().WithMessage("Please enter an End Date");
        RuleFor(m => m.StartDate).NotNull().WithMessage("Please enter a Start Date")
            .LessThan(m => m.EndDate).WithMessage("Start Date must preceed End Date");
    }
}

// declare MyModelValidator as a validator for view model
[Validator(typeof(MyModelValidator))]
public class MyModel
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

如果您有兴趣尝试一下,请务必在撰写本文{{1}时获取FluentValidation.MVC5(或适用于您正在使用的MVC版本)在Beta)nuget中。你所要做的只是在global.asax中注册它,如下所示:

FluentValidation.MVC6

答案 2 :(得分:0)

如何将逻辑添加到类中并实现IValidateObject呢?

document.getElementById('p1').innerHTML = 'This worked';