In my ViewModel I have a property with multiple validation errors like this
[Required(ErrorMessage = "Required")]
[RegularExpression(@"^(\d{1,2})$", ErrorMessage = "Only numbers admitted")]
[MaxLength(3, ErrorMessage = "MaxLength is 3")]
public string MyField { get; set; }
The "Required" validation depends on user input on another field, so in the controller I want to remove the error from the ModelState. The only way to do it that I found is like this:
if (view.OtherField != null && view.OtherField.Trim() != "" && ModelState.ContainsKey("MyField"))
{
//removing all errors from "MyField"
ModelState["MyField"].Errors.Clear();
//checking length
if (view.MyField.Length > 3)
ModelState.AddModelError("MyField", "MaxLength is 3");
//checking the value
Regex regex = new Regex(@"(\d{1,2})");
if (!regex.IsMatch(view.MyField))
ModelState.AddModelError("MyField", "Only numbers admitted");
}
Is there a way to selectively remove only the "Required" error without having to remove the whole ModelState error of the MyField property and then re-adding the other errors?