在过去的两天里,我一直在尝试让客户端自定义验证在 ASP.Net MVC3 上工作。我已经按照此处、此处、此处和此处的示例进行操作,但无法使其运行。有人可以看看我的(当前)代码,如果您发现任何错误,请告诉我,任何帮助将不胜感激
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>