I'm using the MVC Foolproof Validation library to make dependent requirements:
public bool IsRequired { get; set; }
[RequiredIfTrue("IsRequired", ErrorMessage = "This field is required")]
public int RequiredIfTrueSelectID { get; set; }
This works perfectly on the client side, allowing me to submit the form without a RequiredIfTrueSelectID
value (i.e. value is 0), but on the [HttpPost]
the ModelState.IsValid
returns false, and with the following result in the immediate window:
myViewModel.IsRequired
true
ModelState["RequiredIfTrueSelectID"].Errors[0]
{System.Web.Mvc.ModelError}
ErrorMessage: "A value is required."
Exception: null
I'm ensuring that I'm posting back the value of RequiredIfTrueSelectID (as you can see in the first immediate window query above). Why am I getting the "A value is required" message, and how can I suppress this error?
By the way, I'm in MVC5. Maybe the ModelState
implementation has changed since Foolproof's last update 2 years ago? Does anyone else know of a more recently-published library that functions like Foolproof?
Controller method:
[HttpPost]
public virtual ActionResult ValidationTest(TestViewModel vm)
{ //breakpoint here to check ModelState.IsValid
return View(vm);
}
Oh, duh. Your field is a value type.
Value types are always required. You need to make the type nullable if you want it to be optional.
Notice that the error message is not the same as the error message used in your validator, that's the first clue.