我想为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"));
但是它不起作用:(没有客户端验证这种类型的规则(其他类型如需要工作正常)
我做错了什么?
答案 0 :(得分:2)
您不需要更改MicrosoftMvcJQueryValidation.js。我最近不得不自己解决这个问题,以下内容可能有所帮助;
http://www.deepcode.co.uk/2010/08/custom-mvc-2-validation-using-jquery.html
答案 1 :(得分:1)
我会复制粘贴整件事,但我认为你最好只阅读Phil Haack的custom validation in 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(); %>
答案 2 :(得分:1)
看起来您正在将DateCompare属性应用于ViewModel类(而不是属性)。这对于服务器验证有效,但意味着它没有机会选择加入客户端验证。请参阅http://blogs.msdn.com/b/stuartleeks/archive/2010/08/06/asp-net-mvc-adding-client-side-validation-to-propertiesmustmatchattribute.aspx。