如何在自定义验证器中设置通用方法

时间:2012-10-06 23:52:09

标签: c# validation properties customvalidator

我为Custom Validator属性创建了Response。这是代码

public partial class MultipleSelectionQuestion<T> : Question
{
    private ICollection<T> _response;

    public int? MaxSelections
    {
        get { return ((MultipleSelectionQuestionTemplate<T>)this.QuestionTemplate).MaxSelections; }
    }

    public ICollection<T> Range
    {
        get { return ((MultipleSelectionQuestionTemplate<T>)this.QuestionTemplate).Range; }
    }

    [CustomValidation(typeof(CommonValidation), "ValidationMultipleSelectionResponseChoices")]
    [Required]
    public ICollection<T> Response
    {
        get { return _response; }
        set {  SetProperty(ref _response, value, "Response"); }
    }
}

这是我的CommonValidation静态类,我意识到Response属性找不到该方法。问题是通用的。

public static class CommonValidation
{
    public static ValidationResult ValidationMultipleSelectionResponseChoices<T>(IEnumerable<T> value, ValidationContext context)
    {
        var question = (MultipleSelectionQuestion<T>)context.ObjectInstance;
        if (value != null)
        {
            var maxSelections = question.MaxSelections;

            if (maxSelections.HasValue)
            {
                if (value.Count() > maxSelections.Value)
                {
                    return new ValidationResult(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            "Response must have at most {0} selections",
                            maxSelections.Value),
                        new[] { context.MemberName });
                }
            }
        }

        return ValidationResult.Success;
    }
}

0 个答案:

没有答案