【问题标题】:asp.net/MVC custom model validation attribute not workingasp.net/MVC 自定义模型验证属性不起作用
【发布时间】:2018-11-29 15:21:19
【问题描述】:

(我已经取得了一些进展,但仍然无法正常工作,下面更新...)

我正在尝试实现您的开始日期不大于结束日期验证。这是我第一次尝试编写自定义验证属性。根据我在这里读到的内容,这就是我想出的……

自定义验证属性:

public class DateGreaterThanAttribute : ValidationAttribute
{
    private string _startDatePropertyName;

    public DateGreaterThanAttribute(string startDatePropertyName)
    {
        _startDatePropertyName = startDatePropertyName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var propertyInfo = validationContext.ObjectType.GetProperty(_startDatePropertyName);
        if (propertyInfo == null)
        {
            return new ValidationResult(string.Format("Unknown property {0}", _startDatePropertyName));
        }
        var propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance, null);
        if ((DateTime)value > (DateTime)propertyValue)
        {
            return ValidationResult.Success;
        }
        else
        {
            var startDateDisplayName = propertyInfo
                .GetCustomAttributes(typeof(DisplayNameAttribute), true)
                .Cast<DisplayNameAttribute>()
                .Single()
                .DisplayName;

            return new ValidationResult(validationContext.DisplayName + " must be later than " + startDateDisplayName + ".");
        }
    }
}

查看模型:

public class AddTranscriptViewModel : IValidatableObject
{
    ...

    [DisplayName("Class Start"), Required]
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    [RegularExpression(@"^(1[012]|0?[1-9])[/]([12][0-9]|3[01]|0?[1-9])[/](19|20)\d\d.*", ErrorMessage = "Date out of range.")]
    public DateTime? ClassStart { get; set; }

    [DisplayName("Class End"), Required]
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    [RegularExpression(@"^(1[012]|0?[1-9])[/]([12][0-9]|3[01]|0?[1-9])[/](19|20)\d\d.*", ErrorMessage = "Date out of range.")]
    [DateGreaterThan("ClassStart")]
    public DateTime? ClassEnd { get; set; }

    ...
}

前端相关部分:

@using (Html.BeginForm("AddManualTranscript", "StudentManagement", FormMethod.Post, new { id = "studentManagementForm", @class = "container form-horizontal" }))
{
    ...
    <div class="col-md-4" id="divUpdateStudent">@Html.Button("Save Transcript Information", "verify()", false, "button")</div>
    ...
    <div class="col-md-2">
        <div id="divClassStart">
            <div>@Html.LabelFor(d => d.ClassStart, new { @class = "control-label" })</div>
            <div>@Html.EditorFor(d => d.ClassStart, new { @class = "form-control" }) </div>
            <div>@Html.ValidationMessageFor(d => d.ClassStart)</div>
        </div>
    </div>

    <div class="col-md-2">
        <div id="divClassEnd">
            <div>@Html.LabelFor(d => d.ClassEnd, new { @class = "control-label" })</div>
            <div>@Html.EditorFor(d => d.ClassEnd, new { @class = "form-control" }) </div>
            <div>@Html.ValidationMessageFor(d => d.ClassEnd)</div>
        </div>
    </div>
    ...
}

<script type="text/javascript">
    ...
    function verify() {

        if ($("#StudentGrades").data("tGrid").total == 0) {
            alert("Please enter at least one Functional Area for the transcript grades.");
        }
        else {
            $('#studentManagementForm').trigger(jQuery.Event("submit"));
        }
    }
    ...
</script>

我看到的行为是表单上所有其他字段的所有其他验证,这些都是标准验证,如Required、StringLength和RegularExpression等,都按预期工作:当我点击“保存”按钮,未通过的字段显示红色文本。我在 IsValid 代码中放置了一个断点,除非所有其他验证都通过,否则它不会命中。即使这样,如果验证检查失败,它也不会停止发布。

进一步阅读使我将以下内容添加到 Global.asax.cs:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DateGreaterThanAttribute), typeof(DataAnnotationsModelValidator));

但这并没有什么不同。我还在回发函数中测试了ModelState.IsValid,结果是假的。但是对于其他验证者来说,如果永远不会走那么远。我什至在标记中注意到,似乎在生成页面时在具有验证属性的那些字段上创建了很多标记。这种魔法发生在哪里?为什么我的自定义验证器会退出循环?

那里有很多变化,但我在这里看到的似乎与我所看到的大致一致。我还阅读了一些关于在客户端注册验证器的信息,但这似乎只适用于客户端验证,而不适用于提交/发布时的模型验证。如果答案是我的一些愚蠢的疏忽,我不会感到尴尬。大约一天后,我只需要它工作。

更新:

Rob 的回答将我带到了我在下面的评论中引用的链接,然后将我带到了这里client-side validation in custom validation attribute - asp.net mvc 4 又把我带到了这里https://thewayofcode.wordpress.com/tag/custom-unobtrusive-validation/

我在那里读到的内容与我观察到的内容不符,标记中缺少某些内容,看起来作者概述了如何将其放入其中。所以我在我的验证属性类中添加了以下内容:

public class DateGreaterThanAttribute : ValidationAttribute, IClientValidatable // IClientValidatable added here
...
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        //string errorMessage = this.FormatErrorMessage(metadata.DisplayName);
        string errorMessage = ErrorMessageString;

        // The value we set here are needed by the jQuery adapter
        ModelClientValidationRule dateGreaterThanRule = new ModelClientValidationRule
        {
            ErrorMessage = errorMessage,
            ValidationType = "dategreaterthan" // This is the name the jQuery adapter will use, "startdatepropertyname" is the name of the jQuery parameter for the adapter, must be LOWERCASE!
        };

        dateGreaterThanRule.ValidationParameters.Add("startdatepropertyname", _startDatePropertyName);

        yield return dateGreaterThanRule;
    }

并创建了这个 JavaScript 文件:

(function ($) {
    $.validator.addMethod("dategreaterthan", function (value, element, params) {
        console.log("method");
        return Date.parse(value) > Date.parse($(params).val());
    });

    $.validator.unobtrusive.adapters.add("dategreaterthan", ["startdatepropertyname"], function (options) {
        console.log("adaptor");
        options.rules["dategreaterthan"] = "#" + options.params.startdatepropertyname;
        options.messages["dategreaterthan"] = options.message;
    });
})(jQuery);

(请注意 console.log 命中...我从未见过。)

在此之后,当我浏览到 DataGreaterThanAttribute 构造函数和 GetClientValidationRules 中的页面时,我现在得到了点击。同样,ClassEnd 输入标记现在包含以下标记:

data-val-dategreaterthan="The field {0} is invalid." data-val-dategreaterthan-startdatepropertyname="ClassStart"

所以我越来越近了。问题是, addMethod 和 adapater.add 似乎没有做他们的工作。当我使用以下命令在控制台中检查这些对象时:

$.validator.methods
$.validator.unobtrusive.adapters

...我添加的方法和适配器不存在。如果我在控制台中运行我的 JavaScript 文件中的代码,它们会被添加并存在。我还注意到,如果我通常检查不显眼的验证对象...

$("#studentManagementForm").data('unobtrusiveValidation')

...没有证据表明我的自定义验证。

正如我之前提到的,这里有很多例子,而且它们的做事似乎都略有不同,所以我仍在尝试一些不同的事情。但我真的希望以前打败过这个的人能过来和我分享那把锤子。

如果我不能让它工作,我会戴上安全帽并编写一些 hacky JavaScript 来欺骗相同的功能。

【问题讨论】:

    标签: asp.net-mvc razor unobtrusive-validation


    【解决方案1】:

    我认为您的模型需要 IEnumerable

    大约 4 年前,我不得不做类似的事情,如果这有帮助的话,我仍然手头有 sn-p:

    public class ResultsModel : IValidatableObject
    {
        [Required(ErrorMessage = "Please select the from date")]
        public DateTime? FromDate { get; set; }
    
        [Required(ErrorMessage = "Please select the to date")]
        public DateTime? ToDate { get; set; }
    
        IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            var result = new List<ValidationResult>();
            if (ToDate < FromDate)
            {
                var vr = new ValidationResult("The to date cannot be before the from date");
                result.Add(vr);
            }
            return result;
        }
    }
    

    【讨论】:

    • 谢谢,@Rob C。这让我发现模型中已经有一个 Validate 方法——我正在修改现有代码。它会检查以确保 DOB 不适合 17 岁以下的人。所以我试了一下,没有打中。我在代码中放了一个断点,它没有命中。这让我想到了这个:dotnetcurry.com/aspnet-mvc/1083/…——我下载并运行了它,它运行得很好。所以我试图找出这与我所拥有的有何不同。应该没那么难……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多