In this tutorial, you learn how to use the Data Annotation validators to perform validation in an ASP. The advantage of using the Data Annotation validators is that they enable you to perform validation simply by adding one or more attributes – such as the Required or String Length attribute – to a class property. Listing 1: Models\The Product class illustrates how to use one additional attribute: the Display Name attribute.

Before you can use the Data Annotation validators, you must download the Data Annotations Model Binder. Next click the Browse tab and browse to the location where you downloaded (and unzipped) the Data Annotations Model Binder sample (see Figure 1). The Display Name attribute enables you to modify the name of the property when the property is displayed in an error message.

Validating data sfai Dating finder free chating

The validator attributes are applied to the properties of the Movie Meta Data class.

The Title, Director, and Date Released properties are all marked as required properties.

Figure 3: Missing required fields If you enter an invalid currency amount, then the error message in Figure 4 is displayed.

Figure 4: Invalid currency amount If you are using the Microsoft Entity Framework to generate your data model classes then you cannot apply the validator attributes directly to your classes.

String max length 50 public string First Name [Data Member] [Range(2, 100)] public int Age [Data Member] [Required] [Regular Expression(@"\b[A-Z0-9._%-] @[A-Z0-9.-] \.[A-Z]\b", Error Message = "Invalid Mail id")] public string Email Manually Validating Values: You can manually apply the validation test by using the Validator class.

You can call the Validate Property method on the set accessor of a property to check the value against the validation attributes for the property.

Figure 5: Movie class generated by Entity Framework Listing 4: Models\The file in Listing 4 contains two classes named Movie and Movie Meta Data. It corresponds to the partial class generated by the Entity Framework that is contained in the Data Model. Notice that the Movie partial class is decorated with a Metadata Type attribute that points at the Movie Meta Data class.

The Movie Meta Data class contains proxy properties for the properties of the Movie class.

Figure 6: Using validators with the Entity Framework (Click to view full-size image) In this tutorial, you learned how to take advantage of the Data Annotation Model Binder to perform validation within an ASP. You learned how to use the different types of validator attributes such as the Required and String Length attributes.