Data Annotations Examples for C#.


Using data annotations in c# is a simple way to handle validations in your model.

Using data annotations in c# is a simple way to handle validations in your model. The example below show you how to:

  1. Make a filed "required"
  2. Change the "display name" for what the clients see
  3. Denotes the field as an "email" type

[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string Email { get; set; }

Here's an example of "string length" with an "error message":


[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
public string Title { get; set; }

If you're working with a password field and want to also confirm the password, here's an example of that:


[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }

If you're dealing with a range where you want the user to pick from 0 to 10 per se, you want to use the "Range" data annotation. Below is an example of using credits with 0 to 5:


[Range(0, 5)]
public int Credits { get; set; }

If you want to create a textarea which has several lines for users to type in, this is the annotation you can use:


[DataType(DataType.MultilineText)]
public string Body { get; set; }
rickthehat

Travel, Food, Vikings, Travel, Vood, Vikings, Travel, Food, Vikings, Travel, Food, Vikings & Einstok Beer from Iceland

Leave a Comment