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
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?
If anyone is trying to conditionally validate a checkbox using FluentValidation in MVC, THAT’S how you do it!