I'm using FluentValidation to validate input on an MVC form.
I have a checkbox.
No matter what I set the validation rule to, it does not validate the checkbox.
I know validation is working, because I have a dropdownlist that's validating fine on the same page.
View
<%: Html.CheckBoxFor(m => m.fullname_required) %>
Model
[Validator(typeof(CreateFormModelValidator))]
public class CreateFormModel
{
public int? group_id { get; set; }
public IEnumerable<SelectListItem> Groups { get; set; }
[DisplayName("Fullname is required")]
public bool fullname_required { get; set; }
}
public class CreateFormModelValidator : AbstractValidator<CreateFormModel>
{
public CreateFormModelValidator()
{
RuleFor(x => x.group_id).NotEmpty().NotNull().WithMessage("Please select a group!");
RuleFor(x => x.fullname_required).NotNull();
}
}
I've tried
RuleFor(x => x.fullname_required).NotEmpty();
RuleFor(x => x.fullname_required).NotNull();
RuleFor(x => x.fullname_required).NotEqual(false);
None of which work. I'm going bananas trying to make this work. It's an F***ing checkbox
PS: I've found threads talking about using jQuery instead, but this is using server side validation, not client side.
I never placed the ValidationMessageFor attribute on the page for the checkbox. It was validating fine, but I couldn't see it.
UPDATE: The eventual goal was to have one checkbox which is only validated if a second checkbox is checked. Ie
RuleFor(x => x.fullname_show).NotEmpty().When(x => x.fullname_required == true);
However, this still wouldn't work after the facepalm above, but thanks to lomaxx I was able to get it working by converting fullname_required to bool?
RuleFor(x => x.fullname_show).NotEmpty().When(x => ((bool?)x.fullname_required) != false);
If anyone is trying to conditionally validate a checkbox using FluentValidation in MVC, THAT'S how you do it!
I have a theory, and I could be wrong, but a bool is a value type, not a reference type, so by definition it always has a value (i.e. true or false).
So when you're submitting the form, it sees it has a value of false for "unchecked" and assumes that's a valid value.
What you might need to do is change the bool to be nullable in your code so that the default value is "null" rather than false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With