Introduction
In our earlier posts, we initiated our exploration of ASP.NET validation, laying the foundational knowledge of both client-side and server-side validation. We deepened our understanding by examining a real-world example that implemented server-side validation. Subsequently, we discussed various data annotation attributes that enhance our model definitions.
Continuing with this theme, this post will delve into validation helpers. These tools are crucial when errors occur, as they communicate these errors to users, either by alerting them or displaying the errors within the browser.
ASP.NET Core MVC utilizes validation helpers to present validation error messages linked to model properties effectively. They are particularly advantageous for showing error messages adjacent to form fields, which assists users in easily spotting and rectifying input errors.
We will focus on two primary validation helpers: asp-validation-for and asp-validation-summary. These helpers streamline the process of error management in user forms, enhancing user experience by providing immediate, contextual feedback on data entry issues.
asp-validation-for
The asp-validation-for tag helper is used to display validation error messages for a specific model property. It generates markup that associates the error message with the corresponding form field.
Example:
Suppose you have a model class RegisterViewModel with a property Username, and you want to display validation error messages for the Username field.
<!-- FORM FIELD -->
<INPUT ASP-FOR="USERNAME" />
<!-- VALIDATION ERROR MESSAGE -->
<SPAN ASP-VALIDATION-FOR="USERNAME" CLASS="TEXT-DANGER"></SPAN>
asp-for=”Username” generates the input field for the Username property.
asp-validation-for=”Username” generates the validation error message for the Username property.
If there are validation errors for the Username property, ASP.NET Core MVC automatically populates this element with the corresponding error message.
asp-validation-summary
The asp-validation-summary tag helper is used to display a summary of validation errors. It generates markup that lists all validation errors associated with the model.
<!-- VALIDATION SUMMARY -->
<ASP-VALIDATION-SUMMARY CLASS="TEXT-DANGER" />
asp-validation-summary generates a list of all validation errors for the model. If there are any validation errors in the model state, ASP.NET Core MVC automatically populates this element with the corresponding error messages.
ASP.NET Core MVC automatically populates the asp-validation-for and asp-validation-summary tag helpers with error messages from the ModelState dictionary.
How it works
- Validation Process: During model validation, if any validation errors are detected, ASP.NET Core MVC populates the ModelState dictionary with error messages associated with invalid model properties. Each error message is associated with the name of the corresponding model property.
- Rendering the View: When the view is rendered, the Razor engine processes tag helpers and generates HTML markup based on their attributes and properties.
- Validation Helpers Execution: When the Razor engine encounters asp-validation-for and asp-validation-summary tag helpers in the view, it executes them.
- Accessing ModelState: Internally, the validation helpers access the ModelState dictionary to retrieve error messages associated with the model properties.
- Binding to Model Properties: For asp-validation-for, the validation helper binds to a specific model property specified in the asp-for attribute. It retrieves the corresponding error message from the ModelState dictionary based on the property name.
- Aggregating Error Messages: For asp-validation-summary, the validation helper aggregates all validation error messages from the ModelState dictionary and formats them into a summary view.
- Generating HTML Markup: Finally, the tag helpers generate HTML markup with the error messages included. The error messages are injected into the generated HTML at the appropriate locations based on the tag helper configuration and the layout of the view.
Complete Example
Consider a scenario where you have a registration form with multiple fields, and you want to display validation error messages for each field.
Create the RegisterViewModel complete with data annotations. Click here to see a list of data annotation that you can begin with.
PUBLIC CLASS REGISTERVIEWMODEL
{
[REQUIRED(ERRORMESSAGE = "USERNAME IS REQUIRED")]
[STRINGLENGTH(50, MINIMUMLENGTH = 3, ERRORMESSAGE = "USERNAME MUST BE BETWEEN 3 AND 50 CHARACTERS")]
PUBLIC STRING USERNAME { GET; SET; }
}
See below the code for the view showing validation summary and asp-validation-for tag
<FORM ASP-ACTION="REGISTER" METHOD="POST">
<!-- USERNAME FIELD -->
<DIV CLASS="FORM-GROUP">
<LABEL ASP-FOR="USERNAME"></LABEL>
<INPUT ASP-FOR="USERNAME" CLASS="FORM-CONTROL" />
<SPAN ASP-VALIDATION-FOR="USERNAME" CLASS="TEXT-DANGER"></SPAN>
</DIV>
<!-- EMAIL FIELD -->
<DIV CLASS="FORM-GROUP">
<LABEL ASP-FOR="EMAIL"></LABEL>
<INPUT ASP-FOR="EMAIL" CLASS="FORM-CONTROL" />
<SPAN ASP-VALIDATION-FOR="EMAIL" CLASS="TEXT-DANGER"></SPAN>
</DIV>
<!-- OTHER FORM FIELDS... -->
<!-- VALIDATION SUMMARY -->
<ASP-VALIDATION-SUMMARY CLASS="TEXT-DANGER" />
<!-- SUBMIT BUTTON -->
<BUTTON TYPE="SUBMIT" CLASS="BTN BTN-PRIMARY">REGISTER</BUTTON>
</FORM>
In this example:
Each form field has an associated asp-validation-for tag helper to display validation error messages.
The asp-validation-summary tag helper displays a summary of all validation errors at the top of the form.
When the form is submitted, ASP.NET Core MVC automatically performs model validation and populates the validation error messages based on the validation rules specified in the model.
Conclusion
In this post, we’ve demonstrated how ASP.NET Core MVC utilizes validation helpers such as asp-validation-for and asp-validation-summary to enhance the presentation of validation error messages in Razor views. These tools automatically pinpoint model properties and gather error messages from the ModelState dictionary, enabling real-time user feedback on input mistakes. This integration not only simplifies the development workflow but also significantly improves the user experience in ASP.NET Core MVC applications.
Additionally, there are other methods for displaying errors such as JavaScript-based error handling, CSS styling, client-side libraries like jQuery validation, and using partial views or components. We’ll explore some of these methods in future posts.
We highly value your feedback and are eager to hear your thoughts on this discussion. Please feel free to comment below with any feedback or suggest topics you’d like us to explore in upcoming posts. Your insights and experiences are vital in enriching our content and making this series a comprehensive resource for all developers.
If you’re interested in the source code for the examples discussed or have specific implementation questions, please express your interest in the comments. We’re here to assist and provide additional resources to deepen your understanding.
