Fluent Validation in MVC: specify RuleSet for Client-Side validation

≯℡__Kan透↙ 提交于 2019-12-01 17:14:50

After digging in FluentValidation sources I found solution. To tell view that you want to use specific ruleset, decorate your action, that returns view, with RuleSetForClientSideMessagesAttribute:

[HttpGet]
[RuleSetForClientSideMessages("Edit")]
public ActionResult ShopInfo()
{
    var viewModel = OwnedShop.ToViewModel();
    return PartialView("_ShopInfo", viewModel);
}

If you need to specify more than one ruleset — use another constructor overload and separate rulesets with commas:

[RuleSetForClientSideMessages("Edit", "Email", "Url")]
public ActionResult ShopInfo()
{
    var viewModel = OwnedShop.ToViewModel();
    return PartialView("_ShopInfo", viewModel);
}

If you need to decide about which ruleset would be used directly in action — you can hack FluentValidation by putting array in HttpContext next way (RuleSetForClientSideMessagesAttribute currently is not designed to be overriden):

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);
}

Unfortunately, there are no info about this attribute in official documentation.

UPDATE

In newest version we have special extension method for dynamic ruleset setting, that you should use inside your action method or inside OnActionExecuting/OnActionExecuted/OnResultExecuting override methods of controller:

ControllerContext.SetRulesetForClientsideMessages("Edit", "Email");

Or inside 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
    }
}

Adding to this as the library has been updated to account for this situation...

As of 7.4.0, it's possible to dynamically select one or multiple rule sets based on your specific conditions;

ControllerContext.SetRulesetForClientsideMessages("ruleset1", "ruleset2" /*...etc*);

Documentation on this can be found in the latest FluentValidation site: https://fluentvalidation.net/aspnet#asp-net-mvc-5

Adding the CustomizeValidator attribute to the action will apply the ruleset within the pipeline when the validator is being initialized and the model is being automatically validated.

   public ActionResult Save([CustomizeValidator(RuleSet="MyRuleset")] Customer cust) {
   // ...
   }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!