Validate checkbox on the client with FluentValidation/MVC 3

前端 未结 4 1660
迷失自我
迷失自我 2020-12-14 10:15

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 v

4条回答
  •  太阳男子
    2020-12-14 10:49

    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
    {
        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.

提交回复
热议问题