验证与FluentValidation / MVC 3在客户端上复选框 [英] Validate checkbox on the client with FluentValidation/MVC 3

查看:124
本文介绍了验证与FluentValidation / MVC 3在客户端上复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,如果使用FluentValidation在客户端上被选中复选框来验证。我想不出它我们对我的生活。

I am trying to validate if a check box is checked on the client using FluentValidation. I can't figure it our for the life of me.

可以使用它不显眼的审定办?

Can it be done using unobtrusive validation?

推荐答案

让我们假设你有以下型号:

Let's assume that you have the following model:

[Validator(typeof(MyViewModelValidator))]
public class MyViewModel
{
    public bool IsChecked { get; set; }
}

具有以下验证:

public class MyViewModelValidator : AbstractValidator<MyViewModel>
{
    public MyViewModelValidator()
    {
        RuleFor(x => x.IsChecked).Equal(true).WithMessage("Please check this checkbox");
    }
}

和控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

用相应的视图:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.IsChecked)
    @Html.CheckBoxFor(x => x.IsChecked)
    @Html.ValidationMessageFor(x => x.IsChecked)
    <button type="submit">OK</button>
}

的Global.asax 您已经注册了一口流利的验证模型验证提供商:

and in Global.asax you have registered the fluent validation model validator provider:

FluentValidationModelValidatorProvider.Configure();

到目前为止,我们有服务器端验证并运行良好。那很好。这总是第一部分,我们必须设置。我看到有人过分集中于做客户端验证,他们忘记做服务器端验证,当你(如果你偶然发现心怀不轨用户或更糟)禁用javascript,好,不好的事情发生。
到目前为止,我们有信心,因为我们知道,即使得到的东西在客户端上搞砸了我们的域名与服务器端验证保护。

So far we have server side validation up and running fine. That's good. That's always the first part that we must setup. I have seen people focusing too much on doing client side validation that they forget doing server side validation and when you disable javascript (or even worse if you stumble upon a user with bad intentions), well, bad things happen. So far we are confident because we know that even if something gets screwed up on the client our domain is protected with server side validation.

现在让我们照顾客户端验证。开箱FluentValidation.NET支持对 EqualTo 验证自动客户端验证,但对另一个属性值是的 [比较]等价比较时数据注解。

So let's now take care for the client validation. Out of the box FluentValidation.NET supports automatic client validation for the EqualTo validator but when comparing against another property value which is the equivalent of the [Compare] data annotation.

但在我们的例子中,我们是针对一个固定的值进行比较。所以,我们没有得到客户端vaildation开箱。而当我们没有得到的东西开箱,我们需要把它放在盒子。

But in our case we are comparing against a fixed value. So we don't get client side vaildation out of the box. And when we don't get something out of the box, we need to put it in the box.

所以,我们首先来定义一个定制FluentValidationPropertyValidator:

So we start by defining a custom FluentValidationPropertyValidator:

public class EqualToValueFluentValidationPropertyValidator : FluentValidationPropertyValidator
{
    public EqualToValueFluentValidationPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator)
        : base(metadata, controllerContext, rule, validator)
    {
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        if (!this.ShouldGenerateClientSideRules())
        {
            yield break;
        }
        var validator = (EqualValidator)Validator;

        var errorMessage = new MessageFormatter()
            .AppendPropertyName(Rule.GetDisplayName())
            .AppendArgument("ValueToCompare", validator.ValueToCompare)
            .BuildMessage(validator.ErrorMessageSource.GetString());

        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = errorMessage;
        rule.ValidationType = "equaltovalue";
        rule.ValidationParameters["valuetocompare"] = validator.ValueToCompare;
        yield return rule;
    }
}

这是我们要在注册的Application_Start

FluentValidationModelValidatorProvider.Configure(provider =>
{
    provider.AddImplicitRequiredValidator = false;
    provider.Add(typeof(EqualValidator), (metadata, context, description, validator) => new EqualToValueFluentValidationPropertyValidator(metadata, context, description, validator));
});

到目前为止,我们已经联系我们的自定义FluentValidationPropertyValidator与EqualValidator。

So far we have associated our custom FluentValidationPropertyValidator with the EqualValidator.

最后一部分是写一个自定义适配器:

The last part is to write a custom adapter:

(function ($) {
    $.validator.unobtrusive.adapters.add('equaltovalue', ['valuetocompare'], function (options) {
        options.rules['equaltovalue'] = options.params;
        if (options.message != null) {
            options.messages['equaltovalue'] = options.message;
        }
    });

    $.validator.addMethod('equaltovalue', function (value, element, params) {
        if ($(element).is(':checkbox')) {
            if ($(element).is(':checked')) {
                return value.toLowerCase() === 'true';
            } else {
                return value.toLowerCase() === 'false';
            }
        }
        return params.valuetocompare.toLowerCase() === value.toLowerCase();
    });
})(jQuery);    

这就是pretty多少呢。所有剩下的是包括客户端脚本:

And that's pretty much it. All that's left is to include the client scripts:

<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/customadapter.js")" type="text/javascript"></script>

这篇关于验证与FluentValidation / MVC 3在客户端上复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆