I have an asp.net mvc 3 application, and am now trying to add some validation to it. I am testing with a clean solution. I don’t want the validation to occur on the client side (for now), so I have disabled this in Web.config:
<add key="ClientValidationEnabled" value="false"/>
I have a simple class which is implementing IValidatableObject, and I want to use the Validate function for the validation (not attributes).
public class SomeClass : IValidatableObject
{
public int Id { get; set; }
public int LowNumber { get; set; }
public int HighNumber { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (LowNumber > HighNumber)
{
yield return new ValidationResult("LowNumber should not be higher than HighNumber.");
}
}
}
Now to the question. Is server side validation applied automagically, and how? How do I disable this? I want to control this myself – saying something like this in my post action:
[HttpPost]
public string SomeAction(SomeClass model)
{
if (TryValidateModel(model))
return "All good";
else
return "No good";
}
Doing this makes the validation being called – and displayed – twice. Once for this call, and once from someone else. Who?
If you use validation attributes (or the IValidatableObject interface) then the server side validation will always be done when the model is bound using the model binder. If you wanted to override the server side validation I believe you would need to create your own model binder.
Some good information on the topic here and a great article on the binder and the validation pipeline here.