Validate checkbox on the client with FluentValidat

2020-02-08 08:23发布

问题:

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?

回答1:

Let's assume that you have the following model:

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

with the following validator:

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

and a controller:

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

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

with a corresponding view:

@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>
}

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

FluentValidationModelValidatorProvider.Configure();

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.


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.

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.

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

that we are going to register in Application_Start:

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

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

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>


回答2:

I like the Darin Dimitrov's answer, but if you want to do it quickly, here is my alternative way.

Create an additional property in your model, e.g.:

public bool ValidationTrue { get; set; }

and set its value to true in the model's contructor.

Use it in your view to save the value across the requests:

@Html.HiddenFor(x => x.ValidationTrue)

Now add a validation rule like this:

public class MyViewModelValidator : AbstractValidator<MyViewModel>
{
    public MyViewModelValidator()
    {
        RuleFor(x => x.ValidationTrue)
            .Equal(true); // check it for security reasons, if someone has edited it in the source of the page

        RuleFor(x => x.HasToBeChecked)
            .Equal(x => x.ValidationTrue) // HasToBeChecked has to have the same value as ValidationTrue (which is always true)
            .WithMessage("Required");
    }
}

That validation is supported by the unobtrusive validator out-of-the-box.



回答3:

I am coding in ASP.NET MVC5 and Darin's code produces a javascript error on the lines that reference value.ToLowerCase() when a checkbox is involved. Another issue is that this code invalidates the client side equality comparison between two properties. It only seems to work when comparing against a literal value...That may have been his intent, but I need it to work for both situations:

Here's one possible workaround, that involves only two changes to Darin's answer:

First, I updated the javascript function with the following.

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

Secondly, I updated EqualToValueFluentValidationPropertyValidator with the following:

public class EqualToValueFluentValidationPropertyValidator : FluentValidationPropertyValidator
{
    EqualValidator EqualValidator 
    {
        get { return (EqualValidator)Validator; }
    }

    public EqualToValueFluentValidationPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator) : base(metadata, controllerContext, rule, validator) {
        ShouldValidate = false;
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {
        if (!ShouldGenerateClientSideRules()) yield break;

        var propertyToCompare = EqualValidator.MemberToCompare as PropertyInfo;
        if(propertyToCompare != null) {
            // If propertyToCompare is not null then we're comparing to another property.
            // If propertyToCompare is null then we're either comparing against a literal value, a field or a method call.
            // We only care about property comparisons in this case.

            var comparisonDisplayName =
                ValidatorOptions.DisplayNameResolver(Rule.TypeToValidate, propertyToCompare, null)
                ?? propertyToCompare.Name.SplitPascalCase();

            var formatter = new MessageFormatter()
                .AppendPropertyName(Rule.GetDisplayName())
                .AppendArgument("ComparisonValue", comparisonDisplayName);


            string message = formatter.BuildMessage(EqualValidator.ErrorMessageSource.GetString());
            yield return new ModelClientValidationEqualToRule(message, CompareAttribute.FormatPropertyForClientValidation(propertyToCompare.Name)) ;
        }
        else
        {
            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;
        }
    }
}

This code was copied from the EqualToFluentValidationPropertyValidator internal class in the fluentvalidation source, and I added Darin's logic after the else. This allows the client-side validation to work for property comparisons as well as value comparisons...I'm not sure if this is a great approach since you're basically overriding the built-in equality validator and it may break in future releases of fluent validation....but Darin's answer has the same issue.

There might be better ways to handle this. If somebody knows of a way to directly include the logic from the internal EqualToFluentValidationPropertyValidator class, then I'd love to hear it.



回答4:

it's based on @cryss answer

RuleFor(x => x.HasToBeChecked)
        .Equal(x => true)
        .WithMessage("Required");

you don't need to use additional property