【发布时间】:2012-05-28 14:54:42
【问题描述】:
过去两天我一直在尝试让客户端自定义验证在 ASP.Net MVC3 上工作。我遵循了here、here、here 和here 的示例,但无法使其运行。有人可以看看我的(当前)代码,如果您发现任何错误,请告诉我,任何帮助都将不胜感激
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>
【问题讨论】:
-
第一个
return false应该在“客户端验证脚本”中吗?当然它永远不会到达下面以try开头的代码,因为它无法访问? -
抱歉 - 我添加只是为了检查脚本是否正在运行,现在删除 - 仍然没有改进
-
包含
CheckDateValidFormat操作的代码在哪里,你能看到它在你的开发 IDE 中被击中吗 -
@SpaceBison - 不,CheckDateValidFormat 永远不会被击中
-
所以我认为 $.get 中您的控制器操作的路径是错误的 - 如果您切换到 $.ajax 并添加一个
error: function() { etc etc }块,它可能会帮助您找出问题到底是什么,如果不是很明显,但我认为你需要/area/controller/action或类似的东西。
标签: jquery asp.net-mvc-3