ASP.NET Dynamic Data is fantastic in that it automatically picks up simple validation straight from your DBML/EF model.

It will pick up things like required fields, data types and maximum lengths. You can also manually assign validation rules to your classes using metadata and validation attributes.

The following is a list of available validators from the System.ComponentModel.DataAnnotations namespace.

You use these by attribute by creating a metadata class and associating it with your domain class using the MetadataType attribute

[MetadataType(typeof(CustomerMetadata))]
public partial class Customer { }

public class CustomerMetadata
{
	[Required(ErrorMessage = "First Name is a required field")]
	[StringLength(30, ErrorMessage="The customer's first name cannot be more than 30 characters")]
	public object FirstName { get; set; }

	[RegularExpression(@"\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b")]
	public object EmailAddress { get; set; }

	[Range(18,150, ErrorMessage = "Customer must be 18 to 150 years old")]
	public object Age { get; set; }
}

Note: Make sure the partial class is in the same namespace as your DBML/EF classes.

Now you get extra validation with a few lines of code.

Comment