- Part 1 – Overview
- Part 2 – the Label
- Part 3 – the Source Code
- Part 4 – the Partial View
- Part 5 – the Required Field Indicator
The Required Field Indicator
The Required Field Indicator is a property which allows the UI to indicate that a field is required. The example below shows that an asterisk could be used to indicated the field is required. This could be used to apply a css class to the Label which could change the color or bold the label. The possibilities for how you turn this property into a compelling user interface is endless. The important point to know is that there are different approaches to decide how this could be set.
Here is an example of using a DataAnnotations Required attribute as a way to indicate the field is required. I like this approach since this attribute can be used with a Model Binder to perform Model Validation using model state. This model binder will be provided in the ASP.Net MVC 2.0 release so I included this as a way to get synergy with existing features of the MVC framework.
I have received a lot of feed back that people feel marking your model with attributes pollutes the model. I disagree with this because the models that I use are View Models not my Domain entities which represent my business object which will be stored into my database. The Models that I would decorate with validation attributes would be used for one specific MVC View. The model would represent the fields needed to create the User Interface view.
An alternative approach to using attributes would be to use a Fluent method as shown below. I dislike this approach as it does not work with my preferred way of performing data type validation using the MVC Model Binder. in the framework. I would be more likely to use the fluent methods for the Label or PartialView selection, but I would not use it for the Required indicator because it would mean I am duplicating how I identify a required property on my Model.
The View markup
Here is an example of how the Required property is used in the Field.Master master page. As I wrote earlier, this could be used to add a css class to the html markup.
Your own convention
The framework uses a convention to determine if a Model property is required. By implementing your own PropertyIsRequiredConvention you could make all Properties with the name Name & Description required or whatever makes sense for the type of application that you are creating. It could be Username or email if you are creating a consumer facing website the possibilities are endless. But at the end of the day you can have your own convention.
Here is the implementation of my Default Convention for Property Is Required, it is simple and to the point. I could see implementing some sort of Chain of Responsibility pattern here and in the other conventions to have some consistency to your User Interface.