MVC 3 ValidationMessageFor()不会出现

时间:2011-10-17 04:48:14

标签: javascript jquery asp.net asp.net-mvc-3 jquery-validate

我想以dd-mmm-yyyy的形式强制执行日期。我正在使用以下帖子作为指南:

http://blogs.msdn.com/b/stuartleeks/archive/2011/01/25/asp-net-mvc-3-integrating-with-the-jquery-ui-date-picker-and-adding-a-jquery-validate-date-range-validator.aspx

问题: ValidationMessageFor文本将不会显示(在回发和客户端)。有什么建议吗?

更新

通过包含@ Darin-Demintrov的答案,此问题中的代码现在可以正常运行。请注意,选择日期后验证消息仍然存在。要解决此问题,必须根据下面的答案处理DatePicker onChange()事件。

查看模型属性:

    [Required(ErrorMessage = "* required")]
    [Display(Name = "Event Date")]
    [PpcDate]
    public DateTime EventDate { get; set; }

PpcDate ValidationAttribute类:

public class PpcDateAttribute : ValidationAttribute, IClientValidatable, IMetadataAware
{
    /// <summary>
    /// Any valid DateTime is fine; 
    /// the regex verification only happens on the client
    /// </summary>
    public override bool IsValid(object value)
    {
        if (value == null || (value is DateTime))
            return true;
        else
            return false;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format("{0} must be in the form dd-mmm-yyyy", name);
    }

    #region IClientValidatable Members

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.DisplayName),
            ValidationType = "ppcdate"
        };
    }

    #endregion

    #region IMetadataAware Members

    public void OnMetadataCreated(ModelMetadata metadata)
    {
        metadata.DataTypeName = "Date";
    }

    #endregion
}

视图:

@Html.EditorFor(model => model.EventDate)
@Html.ValidationMessageFor(model => model.EventDate)

与javascript联系:

(function ($) {
    // The validator function
    $.validator.addMethod('ppcdate', function (value) {
        if (!value) {
            return true;
        } else {
            return /^\d{2}-\w{3}-\d{4}$/.test(value);
        }

    });

    // The adapter to support ASP.NET MVC unobtrusive validation
    $.validator.unobtrusive.adapters.add('ppcdate', [], function (options) {

        // EDIT: Add next line per Darin's answer below.  
        options.rules['ppcdate'] = true;

        if (options.message) {
            options.messages['ppcdate'] = options.message;
        }
    });
} (jQuery));

结果html肯定看起来不错?

请注意,data-val-ppcdate属性显示为预期...

<div class="t-widget t-datepicker">
  <div class="t-picker-wrap">
    <input autocomplete="off" class="t-input valid" data-val="true" data-val-ppcdate="Event Date must be in the form dd-mmm-yyyy" data-val-required="* required" id="EventDate" name="EventDate" value="28-Sep-2011" type="text">
    <span class="t-select">
      <span class="t-icon t-icon-calendar" title="Open the calendar">Open the calendar</span>  
    </span>
  </div>
</div>
<span class="field-validation-valid" data-valmsg-for="EventDate" data-valmsg-replace="true"></span>

有什么建议吗?

3 个答案:

答案 0 :(得分:3)

您忘记注册规则,并且您的自定义ppcdate验证方法永远不会触发:

$.validator.unobtrusive.adapters.add('ppcdate', [], function (options) {
    if (options.message) {
        // This is what associates the adapter with the custom validation method
        options.rules['ppcdate'] = options.params;
        options.messages['ppcdate'] = options.message;
    }
});

这是一个完整的example

答案 1 :(得分:0)

加载fiddler并查看您的CSS文件是否未加载。我知道如果CSS没有加载,摘要将不会显示,所以我必须假设同样适用于单个验证项。

答案 2 :(得分:0)

达林的答案解释了为什么规则没有解雇。另一个怪癖是,当DatePicker onChange()事件触发时,我必须强制进行验证。否则,验证仅在用户在日期输入上单击或标记 时触发。如果他们打开和关闭DatePicker,则验证消息仍然存在,即使日期有效。我正在使用Telerik控件,所以它看起来像这样:

Date.ascx文件(日期控制):

<%= Html.Telerik().DatePickerFor(m => m)
    .Format("dd-MMM-yyyy")
    .Value(ViewData["selectedDate"] as DateTime?)
    .ClientEvents(e => { e.OnChange("PPC_validateTelerikDate"); })
%>

<强>的Javascript

/*****************************************************************************
    PPC_validateTelerikDate()
    Force validation to run on the target input.  
    This function allows one to validate when the date picker changes.
    Otherwise, validation only runs when clicking the input element directly
    or tabbing through.
*****************************************************************************/
function PPC_validateTelerikDate(e) {
    // get the form validation object
    var val = $(e.target.form).validate();
    // now validate the target
    val.element($(e.target));
}