Server Side Validation With ASP.NET MVC
When you’re using ASP.NET MVC, there’s no validation controls for you compared to ASP.NET WebForms. It is always important to validate data on the server as well as the client. Back when Dynamic Data was being developed, a set of attributes was created to help tell the Dynamic Data folks about validation and other metadata so they could create smart scaffolds. What this allows you to do is decorate your classes or properties with validation attributes. A project that is available on CodePlex gives you the power to inject this validation into your MVC project. The CodePlex project can be found here. The end results are you can decorate your classes with some of the following attributes to perform server side validation:
- Required – a required field
- StringLength – allows you to set the minimum and maximum length of a string
- RegularExpression – performs regular expression validation
When you use this your validation classes will look like the following example:
Via C#
1: public class EmployeeMetaData
2: {
3: [Required]
4: [StringLength(10, ErrorMessage="Given name cannot be more than 10 characters")]
5: public string GivenName { get; set; }
6:
7: [Required]
8: public string Surname { get; set; }
9: }
Via VB
1: Public Class EmployeeMetaData
2: Private privateGivenName As String
3: <Required, StringLength(10, ErrorMessage:="Given name cannot be more than 10 characters")> _
4: Public Property GivenName() As String
5: Get
6: Return privateGivenName
7: End Get
8: Set(ByVal value As String)
9: privateGivenName = value
10: End Set
11: End Property
12:
13: Private privateSurname As String
14: <Required> _
15: Public Property Surname() As String
16: Get
17: Return privateSurname
18: End Get
19: Set(ByVal value As String)
20: privateSurname = value
21: End Set
22: End Property
23: End Class
