Evg*_*vin 6 validation asp.net-mvc fluentvalidation unobtrusive-validation asp.net-mvc-4
在我的ASP.NET MVC 4项目中,我有一个我的视图模型的验证器,它包含RuleSets的规则定义.Edit当所有客户端验证通过时,在Post操作中使用的规则集.Url和Email规则集规则集中使用的Edit规则(您可以在下面看到)和特殊的ajax操作,它们仅相应地验证电子邮件和仅验证Url.
我的问题是视图不知道它应该使用Edit规则集来生成客户端html属性,并使用default规则集,它是空的.如何判断视图使用Edit规则集进行输入属性生成?
模型:
public class ShopInfoViewModel
{
public long ShopId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Description { get; set; }
public string Email { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
验证器:
public class ShopInfoViewModelValidator : AbstractValidator<ShopInfoViewModel>
{
public ShopInfoViewModelValidator()
{
var shopManagementService = ServiceLocator.Instance.GetService<IShopService>();
RuleSet("Edit", () =>
{
RuleFor(x => x.Name)
.NotEmpty().WithMessage("Enter name.")
.Length(0, 255).WithMessage("Name length should not exceed 255 chars.");
RuleFor(x => x.Description)
.NotEmpty().WithMessage("Enter name.")
.Length(0, 10000).WithMessage("Name length should not exceed 10000 chars.");
ApplyUrlRule(shopManagementService);
ApplyEmailRule(shopManagementService);
});
RuleSet("Url", () => ApplyUrlRule(shopManagementService));
RuleSet("Email", () => ApplyEmailRule(shopManagementService));
}
private void ApplyUrlRule(IShopService shopService)
{
RuleFor(x => x.Url)
.NotEmpty().WithMessage("Enter url.")
.Length(4, 30).WithMessage("Length between 4 and 30 chars.")
.Matches(@"[a-z\-\d]").WithMessage("Incorrect format.")
.Must((model, url) => shopService.Available(url, model.ShopId)).WithMessage("Shop with this url already exists.");
}
private void ApplyEmailRule(IShopService shopService)
{
// similar to url rule: not empty, length, regex and must check for unique
}
}
Run Code Online (Sandbox Code Playgroud)
验证操作示例:
public ActionResult ValidateShopInfoUrl([CustomizeValidator(RuleSet = "Url")]
ShopInfoViewModel infoViewModel)
{
return Validation(ModelState);
}
Run Code Online (Sandbox Code Playgroud)
获取和发布操作ShopInfoViewModel:
[HttpGet]
public ActionResult ShopInfo()
{
var viewModel = OwnedShop.ToViewModel();
return PartialView("_ShopInfo", viewModel);
}
[HttpPost]
public ActionResult ShopInfo(CustomizeValidator(RuleSet = "Edit")]ShopInfoViewModel infoViewModel)
{
var success = false;
if (ModelState.IsValid)
{
// save logic goes here
}
}
Run Code Online (Sandbox Code Playgroud)
视图包含下一个代码:
@{
Html.EnableClientValidation(true);
Html.EnableUnobtrusiveJavaScript(true);
}
<form class="master-form" action="@Url.RouteUrl(ManagementRoutes.ShopInfo)" method="POST" id="masterforminfo">
@Html.TextBoxFor(x => x.Name)
@Html.TextBoxFor(x => x.Url, new { validationUrl = Url.RouteUrl(ManagementRoutes.ValidateShopInfoUrl) })
@Html.TextAreaFor(x => x.Description)
@Html.TextBoxFor(x => x.Email, new { validationUrl = Url.RouteUrl(ManagementRoutes.ValidateShopInfoEmail) })
<input type="submit" name="asdfasfd" value="?????????" style="display: none">
</form>
Run Code Online (Sandbox Code Playgroud)
结果html输入(没有任何客户端验证属性):
<input name="Name" type="text" value="Super Shop"/>
Run Code Online (Sandbox Code Playgroud)
在挖掘FluentValidation源代码后,我找到了解决方案.要告诉视图您要使用特定规则集,请使用以下命令修饰返回视图的操作RuleSetForClientSideMessagesAttribute:
[HttpGet]
[RuleSetForClientSideMessages("Edit")]
public ActionResult ShopInfo()
{
var viewModel = OwnedShop.ToViewModel();
return PartialView("_ShopInfo", viewModel);
}
Run Code Online (Sandbox Code Playgroud)
如果需要指定多个规则集 - 使用另一个构造函数重载并使用逗号分隔规则集:
[RuleSetForClientSideMessages("Edit", "Email", "Url")]
public ActionResult ShopInfo()
{
var viewModel = OwnedShop.ToViewModel();
return PartialView("_ShopInfo", viewModel);
}
Run Code Online (Sandbox Code Playgroud)
如果您需要确定将直接使用哪个规则集 - 您可以通过在下一个方向将数组放入HttpContext来破解FluentValidation(RuleSetForClientSideMessagesAttribute当前不是为了覆盖):
public ActionResult ShopInfo(validateOnlyEmail)
{
var emailRuleSet = new[]{"Email"};
var allRuleSet = new[]{"Edit", "Url", "Email"};
var actualRuleSet = validateOnlyEmail ? emailRuleSet : allRuleSet;
HttpContext.Items["_FV_ClientSideRuleSet"] = actualRuleSet;
return PartialView("_ShopInfo", viewModel);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,官方文档中没有关于此属性的信息.
UPDATE
在最新版本中,我们有动态规则集设置的特殊扩展方法,您应该在操作方法内部或控制器内部OnActionExecuting/ OnActionExecuted/ OnResultExecuting覆盖方法中使用:
ControllerContext.SetRulesetForClientsideMessages("Edit", "Email");
Run Code Online (Sandbox Code Playgroud)
或者在custom ActionFilter/中ResultFilter:
public class MyFilter: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
((Controller)context.Controller).ControllerContext.SetRulesetForClientsideMessages("Edit", "Email");
//same syntax for OnActionExecuted/OnResultExecuting
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3293 次 |
| 最近记录: |