I have a guest book form created using asp.net mvc.
The valid gender form field must be filled in by selecting a value from a drop down control. The drop down control has 3 options, i.e., “–Select–“, “Female”, “Male” and the “–Select–” is selected by default. The data model has been setup to force the visitor select either female or male but not “–Select–“.
We know that the visitor has a chance to temper the form data, so he can submit the gender form field pointing to a value that does not exist in the database.
My question is:
- Can DataAnnotation prevent the user from posting a form field that does not exist in a database?
- What is the preferred approach to counter this attempt? Do I have to check the submitted gender form field first before invoking
SaveChanges()?
It depends whether you need to provide the user with a specific error, or a clean validation message. In cases where the user is trying to tamper with the form post, I would not be too concerned about the user experience.
If you care about this, you can use the
IValidatableObjectinterface to perform a validation against the legal values:The Model validation performs validation using
IValidatableObjectjust as it does using data annotation validation.On the other hand, if you don’t care about the user experience, you could let the error happen in the database, and handle the issue using your standard error handling pipeline. Assuming your foreign key constraints are in place, the operation will fail because the Gender value is not found in the Genders table, or whatever your setup may be.