问题描述
我正在寻求在MVC4中实现自定义客户端验证.目前,我的模型可以使用标准属性,例如我的模型中
I'm looking to implement custom client side validation in MVC4. I currently have it working well with the standard attributes, such as this in my model
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客户端验证.当前,有效路径"仅在服务器端起作用.始终需要在服务器端进行验证,因为只有服务器才能验证路径是否有效,而您不能在此客户端进行验证.
So StringLength and Required both are automatically translated into some JQuery client side validation. Currently "Valid Path" only works server side. The validation will always be required to be server side as only the server can validate if the path is valid, you couldn't do this client side.
服务器端代码如下
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"和"GetClientValidationRules".我写完书
And this works fine. Now I would like this to happen via an ajax call, step in "IClientValidatable" and "GetClientValidationRules". Following my book I have written
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引用).
I believe I now have to write some custom validation script code, the adapter (to identify the required metadata) and the validation rule itself (the validator, referenced by rule.ValidationType).
我认为我不需要编写适配器,我可以使用
I don't think I need to write an adapter, I can just use
所以我现在在UploadedFiles.js中
So in UploadedFiles.js I now have
$.validator.unobtrusive.adapters.addBool("validpath", "required");
在我看来
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/Scripts/UploadedFiles.js")
}
我相信这足以钩住所有内容,但是现在我需要编写javascript验证程序.这些位于jQuery.validator对象中,可以与$ .validator.addMethod添加在一起.
I believe this is enough to hook everything up, but I now need to write the javascript validator. These live in the jQuery.validator object and can be added with $.validator.addMethod.
由于某些原因,我在这里有些不知所措:
This is where I come a bit unstuck for several reasons:
1)这是正确的方法吗,如果我的验证工作在服务器端,那么这是ajax调用吗?然后,这将需要同步.
1) Is this the correct way about things, if my validation lives server side then is this an ajax call? This will then need to be synchronous.
2)是否有我应该重复使用的jQuery元素?我希望我已经完成了工作服务器端工作,因此我可以启用某种魔术功能将客户端连接到它(类似于标准验证).
2) Is there an element of jQuery I should be reusing to do this? I had hoped given I've done the work server side I could just enable some magic to hook up the client side to it (much like the standard validation).
3)我希望它可以在各种自定义验证属性中重复使用.我该如何使它通用?
3) I would like this to be reusable, across various custom validation attributes. How can I make this generic?
如果我从I鼠山上爬了一座山,我深表歉意.谢谢您的时间:)
Apologies if I've made a mountain out of a mole hill. Thanks for your time :)
俄罗斯
推荐答案
MVC附带了RemoteAttribute
,它在内部对控制器方法进行ajax调用,该方法返回一个Json值,指示验证是成功还是失败
MVC comes with RemoteAttribute
which internally makes an ajax call to a controller method that returns a Json value indicating if validation succeeded or failed
public JsonResult IsValid(string SourceDirectory)
{
if (someCondition) //test if the value of SourceDirectory is valid
{
return Json(true, JsonRequestBehavior.AllowGet); // indicates its valid
}
else
{
return Json(false, JsonRequestBehavior.AllowGet); // indicates its not valid
// or return Json("A custom error message that overrides the default message defined in the attribute");
}
}
并用
[Remote("IsValid", "YourController", ErrorMessage = "The path is not valid")]
public string SourceDirectory { get; set; }
注意:RemoteAttribute
仅用于客户端(jquery非侵入式验证),您可能仍需要其他服务器端验证.
Note: The RemoteAttribute
is only for client side (jquery unobtrusive validation) and you may still need additional server side validation.
引用如何:在ASP.NET中实现远程验证MVC (详细示例)
这篇关于MVC4和IClientValidatable-服务器端验证的自动AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!