Add Required Assembly
You need the necessary assembly referenced in your project to use Data Annotation validators. The System.ComponentModel.DataAnnotations namespace contains the validation attributes you'll use.
Apply Validation Attributes to Model Properties
Decorate your model properties with Data Annotation validation attributes to specify validation rules. Some of the validation attributes include [Required], [StringLength], [Range], [EmailAddress], [RegularExpression], etc.
Example
using System.ComponentModel.DataAnnotations;
public class MyModel
{
[Required(ErrorMessage = "The Name field is required.")]
public string Name { get; set; }
[StringLength(50, MinimumLength = 5,
ErrorMessage = "The {0} must be at least {2} characters long and at most {1}.")]
public string Description { get; set; }
[Range(18, 100, ErrorMessage = "The Age must be between {1} and {2}.")]
public int Age { get; set; }
[EmailAddress(ErrorMessage = "Invalid email address.")]
public string Email { get; set; }
[Phone(ErrorMessage = "Invalid phone number.")]
public string PhoneNumber { get; set; }
[Url(ErrorMessage = "Invalid URL format.")]
public string Website { get; set; }
[CreditCard(ErrorMessage = "Invalid credit card number.")]
public string CreditCardNumber { get; set; }
[RegularExpression(@"^\d{5}(-\d{4})?$",
ErrorMessage = "Invalid ZIP code format.")]
public string ZipCode { get; set; }
[Compare("Password", ErrorMessage = "Passwords do not match.")]
public string ConfirmPassword { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime BirthDate { get; set; }
[Timestamp] // Used for concurrency checks
public byte[] RowVersion { get; set; }
}
Navigation Property
//===============================================
//==============================================================
//============================================================================
//==========================================================================