Sunday, November 27, 2011

Learning MVC: A Quick Note on Validation

What is the easiest way to validate class properties that have to be stored in a database - for example, if a database field "Title" has a limit of 50 characters, how do I enforce it best? I could set a "Required" attribute directly on the class property, but the Visual Studio Designer that generated this class may not like it. And anyway, if ever need to change the model and regenerate the database, the attribute is likely to be wiped anyway.

A better idea may be to specify a special class that will handle validation ("buddy class" - funny name which seems to be an official term). I can add a partial declaration to the existing class which will not be wiped if the model changes, and in this declaration I will specify the class that handles validation. As long as the property names of the buddy class exactly match those of the actual class, I should be fine and the valiation will be handled for me by my model!

The code looks like that:

[MetadataType(typeof(InBasket_Validation))]
public partial class InBasket
{

}

public class InBasket_Validation
{
[Required(ErrorMessage = "Title is Required")]
[StringLength(100, ErrorMessage = "Title can not be longer than 100 characters")]
public string Title { get; set; }

[Required(ErrorMessage = "Content is Required")]
[StringLength(5000, ErrorMessage = "Content can not be longer than 5000 characters")]
public string Content { get; set; }
}

The Metadata attribute specifies the buddy class, and the buddy class specifies validation requirements. The partial InBasket class is empty cause I don't want to add anything to the actual class functionality. The code builds (why wouldn't it? It's more important if it works), and I'll test it when I'm done with the views.

by . Also posted on my website

No comments: