簡體   English   中英

ASP.NET MVC2自定義jQuery驗證:客戶端

[英]ASP.NET MVC2 Custom jQuery validation: client -side

我想為2個日期選擇器創建一個驗證規則(startDate少於endDate)。

我創建了一個驗證屬性:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class DateCompareAttribute : ValidationAttribute
{
    private const string _defaultErrorMessage = "'{0}' is less then '{1}'.";

    public DateCompareAttribute(string startDateProperty, string endDateProperty)
        : base(_defaultErrorMessage)
    {
        StartDateProperty = startDateProperty;
        EndDateProperty = endDateProperty;
    }

    public string StartDateProperty { get; private set; }
    public string EndDateProperty { get; private set; }


    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, StartDateProperty, EndDateProperty);
    }

    public override bool IsValid(object value)
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
        object startValue = properties.Find(StartDateProperty, true).GetValue(value);
        object endValue = properties.Find(EndDateProperty, true).GetValue(value);
        if (startValue.GetType() == typeof(DateTime?) && endValue.GetType() == typeof(DateTime?))
        {
            var start = ((DateTime?)startValue);
            var end = ((DateTime?)endValue);
            return (start.Value < end.Value);
        }
        return false;
    }
}

並將ti添加到我的Dto:

[DateCompare("StartDate", "EndDate")]
public class QualificationInput{...}

我創建了一個驗證器:

public class DateCompareValidator : DataAnnotationsModelValidator<DateCompareAttribute>
{
    string startField;
    private string endField;
    string _message;

    public DateCompareValidator(ModelMetadata metadata, ControllerContext context, DateCompareAttribute attribute)
        : base(metadata, context, attribute)
    {
        startField = attribute.StartDateProperty;
        endField = attribute.EndDateProperty;
        _message = attribute.ErrorMessage;
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = _message,
            ValidationType = "dateCompare"
        };
        rule.ValidationParameters.Add("startField", startField);
        rule.ValidationParameters.Add("endField", endField);

        return new[] { rule };
    }
}

並在Application_Start()中的Global.asax.cs中注冊:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DateCompareAttribute), typeof(DateCompareValidator));

在MicrosoftMvcJQueryValidation.js中,我做了以下更改:

switch (thisRule.ValidationType)
{
.....
   case "dateCompare":
      __MVC_ApplyValidator_DateCompare(rulesObj,
      thisRule.ValidationParameters["startField"], thisRule.ValidationParameters["endField"]);
      break;
.....
}

function __MVC_ApplyValidator_DateCompare(object, startField, endField) {
    object["startField"] = startField;
    object["endField"] = endField;
}

jQuery.validator.addMethod("dateCompare", function(value, element, params) {
    if ($('#' + params["startField"]).val() < $('#' + params["endField"]).val())
    { return true; }
    return false;
}, jQuery.format("Error"));

但它不起作用:(沒有客戶端驗證這種類型的規則(其他類型如需要工作正常)

我做錯了什么?

您不應該更改MicrosoftMvcJQueryValidation.js。 我最近不得不自己解決這個問題,以下內容可能有所幫助;

http://www.deepcode.co.uk/2010/08/custom-mvc-2-validation-using-jquery.html

我會復制粘貼整個東西,但我認為你最好只閱讀Phil Haack的MVC自定義驗證指南

首先,我們需要一個模型類。 讓我們像客戶一樣做一些簡單的事情:

public partial class Customer
{
    public string Name { get; set; }
    public int Age { get; set; }
}

然后你的驗證邏輯

[MetadataType(typeof(CustomerMetaData))]
public partial class Customer
{
    class CustomerMetaData
    {
        [Required(ErrorMessage="You must supply a name for a customer.")]
        [StringLength(50, ErrorMessage = "A customer name cannot exceed 50 characters.")]
        public string Name { get; set; }
    }
}

然后連接你的腳本

<script type="text/javascript" src="../../Scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.validate.min.js"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftMvcJQueryValidation.js"></script>

最后,在表單標記開始之前的某處,將以下標記添加到視圖代碼中:

<% Html.EnableClientValidation(); %>

看起來您正在將DateCompare屬性應用於ViewModel類(而不是屬性)。 這對於服務器驗證有效,但意味着它沒有機會選擇加入客戶端驗證。 請參閱http://blogs.msdn.com/b/stuartleeks/archive/2010/08/06/asp-net-mvc-adding-client-side-validation-to-propertiesmustmatchattribute.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM