我正在寻找在 MVC4 中实现自定义客户端验证。我目前让它与标准属性配合得很好,例如我的模型中的这个
public class UploadedFiles
{
[StringLength(255, ErrorMessage = "Path is too long.")]
[Required(ErrorMessage = "Path cannot be empty.")]
[ValidPath]
public string SourceDirectory { get; set; }
}
因此 StringLength 和 required 都会自动转换为一些 JQuery 客户端验证。目前“有效路径”仅适用于服务器端。验证始终需要在服务器端进行,因为只有服务器可以验证路径是否有效,您不能在客户端执行此操作。
服务器端代码如下
public class ValidPathAttribute : ValidationAttribute, IClientValidatable
{
public string SourceDirectory;
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string path = value.ToString();
string message = string.Empty;
var fileSystemSupport = new FileSystemSupport(Settings, new WrappedFileSystem(new FileSystem()));
if (fileSystemSupport.ValidateNetworkPath(path, out message))
{
return ValidationResult.Success;
}
return new ValidationResult(message);
}
}
这很好用。现在我希望通过 ajax 调用来实现这一点,进入“IClientValidatable”和“GetClient ValidationRules”。继我写的书之后
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "validpath";
yield return rule;
}
我相信我现在必须编写一些自定义验证脚本代码、适配器(用于识别所需的元数据)和验证规则本身(验证器,由rule.ValidationType引用)。
我认为我不需要编写适配器,我可以使用
addBool- 为“打开”或“关闭”的验证器规则创建适配器。该规则不需要额外的参数
所以在 UploadedFiles.js 我现在有
$.validator.unobtrusive.adapters.addBool("validpath", "required");
在我看来
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/Scripts/UploadedFiles.js")
}
I believe这足以连接所有内容,但我现在需要编写 javascript 验证器。它们位于 jQuery.validator 对象中,可以使用 $.validator.addMethod 添加。
由于以下几个原因,这就是我有点困惑的地方:
1)这是正确的处理方式吗?如果我的验证位于服务器端,那么这是一个ajax调用吗?这需要同步。
2)是否有一个我应该重用的 jQuery 元素来做到这一点?我希望既然我已经完成了服务器端的工作,我可以启用一些魔法来将客户端连接到它(就像标准验证一样)。
3)我希望它可以在各种自定义验证属性中重复使用。我怎样才能使这个通用?
如果我把鼹鼠山变成一座山,我很抱歉。谢谢你的时间 :)
Russ