Whenever there is some custom validation to do or any fiddling with ModelState I had to rely on magic strings (that reflect property names) so far. Surely there must be a better way.
say you have a form with 2 submit buttons. You’ve already set validation rules by adding Required attributes:
public class MyModel
{
[Required]
public string ValueOne { get; set; }
[Required]
public string ValueTwo { get; set; }
}
This will always validate both fields. But say I’ve added two buttons to the form showing and editor for above model. Button one only requires ValueOne and button two only required ValueTwo.
Typically I would have custom validation code that checks which button was clicked and do something along the lines:
private void ValidateViewModel(MyModel viewModel)
{
foreach (var key in ModelState.Keys)
ModelState[key].Errors.Clear();
if (Request[{ButtonOneName}] != null && string.IsNullOrEmpty(viewModel.ValueOne))
ModelState.AddModelError("ValueOne", "Required");
else if (Request[{ButtonTwoName}] != null && string.IsNullOrEmpty(viewModel.ValueTwo))
ModelState.AddModelError("ValueTwo", "Required");
}
Not very pretty, I know but … My beef is with magic string “ValueOne” and “ValueTwo”. Also with the way errors are cleared out. Is there a way to generate those keys? I’m looking for something like:
ModelState.KeyFor<MyModel>(m => m.ValueOne)
And then a logical extension:
ModelState.Get<MyModel>(m => m.ValueOne)
Before I start reinventing the wheel – is there something like this hidden somewhere already?
Before you ask, I normally define static class SubmitActions, containing constant strings that represent submit button names. And no, I can’t split it up into multiple forms because of the was the view is rendered.
Thanks for any suggestions.
There is a Model Validation Improvements in MVC 3, which will make you be able to check validate based on property related to each other
So by using the IValidatableObject interface built-into .NET 4 to implement a custom validation method on a class. This method can apply validation rules across multiple properties and yield back multiple validation errors,
Have you look at it?
Model Validation Improvements part