I'm trying to validate a model containing other objects with validation rules using the TryUpdateModel:
public class Post
{
public User User;
}
public class User : IValidatableObject
{
public string Captcha;
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (/* check if captcha valid */)
{
yield return new
ValidationResult("Captcha invalid.",
new[] { "Captcha" });
}
}
public ActionResult Edit(int postId, string title)
{
var post = postsRepository.Get(postId);
if (TryUpdateModel(post))
{
/* save */
}
}
The problem is that nested user is also validated but this is updating of the post and there is no captcha field in the form so modelstate always is invalid. How can I validate only value-type properties of the post?
I don't particularly agree with having a CAPTCHA check on a user model unless you require a CAPTCHA everywhere you use the User
model.
That being said, you could...