I would like to use the built-in validation features as far as possible. I would also like to use the same model for CRUD methods.
However, as a drop down list cannot be done using the standard pattern, I have to validate it manually. In the post back method, I would like to just validate the drop down list and add this result to ModelState so that I don't have to validate all the other parameters which are done with Data Annotation. Is it possible to achieve this?
I may be mistaken about the drop down list, but from what I read, the Html object name for a drop down list cannot be the same as the property in the Model in order for the selected value to be set correctly. Is it still possible to use Data Annotation with this workaround?
Thanks.
You can use the addModelError
ModelState.AddModelError(key,message)
when you use that, it will invalidate the ModelState so isValid
will return false.
Update
after seeing the comment to @Pieter's answer
If you want to exclude an element from affecting the isValid()
result, you can use the ModelState.Remove(field)
method before calling isValid()
.
Another option is to inherit IValidatableObject
in your model. Implement its Validate
method and you can leave all other validation in place and write whatever code you want in this method. Note: you return an empty IEnumerable<ValidationResult>
to indicate there were no errors.
public class Class1 : IValidatableObject { public int val1 { get; set; } public int val2 { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { var errors = new List<ValidationResult>(); if (val1 < 0) { errors.Add(new ValidationResult("val1 can't be negative", new List<string> { "val2" })); } if (val2 < 0) { errors.Add(new ValidationResult("val2 can't be negative", new List<string> { "val2" })); } return errors; } }
EDIT: After re-reading the question I don't think this applicable to this case, but I'm leaving the answer here in case it helps someone else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With