mvc3 jquery客户端自定义验证未运行

时间:2012-05-28 14:54:43

标签: jquery asp.net-mvc-3

我一直在努力让ASP.Net MVC3上最近两天的客户端自定义验证工作。我已按照示例herehereherehere进行操作,但无法运行。有人可以查看我的(当前)代码,如果您发现任何错误,请告诉我,任何帮助都将非常感谢

Web.Config同时具有ClientValidationEnabled& UnobtrusiveJavaScriptEnabled设置为true

_Layout.cshtml引用文件如下

<script src="@Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/DateFormatValidator.js")" type="text/javascript"></script>

服务器端验证类定义如下

public class DateFormatValidation : ValidationAttribute, IClientValidatable
{
    public string ValidDateFormat { get; set; }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var modelClientValidationRule = new ModelClientValidationRule
        {
            ValidationType = "validatedate",  // the name of the validation rule as specified in DateFormatValidator.js
            ErrorMessage = LocalisationStrings.InvalidDateFormat
        };

        modelClientValidationRule.ValidationParameters["name"] = ValidDateFormat;
        yield return modelClientValidationRule;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {            
        var dateString = (string) value;
        if(String.IsNullOrEmpty(dateString))
        {
            return ValidationResult.Success;
        }

        // if we can't convert to a date based on the current culture then we will get a null back from the ConvertLocalDateFormatToISO extension method
        if(String.IsNullOrEmpty(dateString.ConvertLocalDateFormatToISO()))
        {
            return new ValidationResult(LocalisationStrings.InvalidDateFormat);
        }
        return ValidationResult.Success;
    }
}

视图模型定义如下

public class SearchViewModel : ElectronicDocument
{

    #region Properties

    [DateFormatValidation(ValidDateFormat="validatedate")] // addig the paramter to the attribute is just a test to get this to work
    public string DueDateFrom
    {
        get;            
        set;             
    }

    [DateFormatValidation]
    public string DueDateTo
    {
        get;
        set;             
    }

客户端验证脚本如下:

(function ($) {
$.validator.addMethod('validatedateformat', function (value, element, param) {
    if (!value) { return true; }
    try {
        var isValidDate = false;
        /* - CheckDateValidFormat is available from the base controller class  */
        $.get('CheckDateValidFormat(' + value +')',
            function (data) {                  
                isValidDate = data;
            });
        if (isValidDate) {
            return true;
        }
        return false;
    }
    catch (e) {
        return false;
    }
});

$.validator.unobtrusive.adapters.add('validatedate', ['name'], function (options) {
    options.rules["validatedateformat"] = options.params.name;
    if (options.message) options.messages["validatedateformat"] = options.message;
});

}(jQuery));

最后视图如下:

<td style="font-size:10px; white-space:nowrap; color: #666">               
           @Html.TextBox("DocumentDateFrom", Model.DocumentDateFrom, new { @class = "date", style = "width:90px;" })
        to @Html.TextBox("DocumentDateTo", Model.DocumentDateTo, new { @class = "date", style = "width:90px;" })</td>

1 个答案:

答案 0 :(得分:2)

您包括jquery-1.8.11.min.js。此版本的jQuery不存在,因为最新版本是1.7.2。

我怀疑你包含 jQuery UI (最新版本1.8.20),你认为这是 jQuery 。确保您使用的是正确的文件。