Skip to content

Instantly share code, notes, and snippets.

@miklund
Created December 28, 2015 12:11
Show Gist options
  • Select an option

  • Save miklund/108a553a92ca715981a4 to your computer and use it in GitHub Desktop.

Select an option

Save miklund/108a553a92ca715981a4 to your computer and use it in GitHub Desktop.
2009-11-07 Data Annotations
# Title: Data Annotations
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2009/11/07/data-annotations.html
var person = new Person
{
Name = "John Doe",
Age = 54,
Email = "[email protected]"
};
/* Validate */
var result = person.ValidateAnnotations();
[MetadataType(typeof(IPerson))]
public class Person : IPerson
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
public interface IPerson
{
[StringLength(20), Required(ErrorMessage = "Name is a required property")]
string Name { get; set; }
[Range(0, 150)]
int Age { get; set; }
[RegularExpression(@"(?i:^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$)")]
string Email { get; set; }
}
public class Person
{
[StringLength(20), Required(ErrorMessage = "Name is a required property")]
public string Name { get; set; }
[Range(0, 150)]
public int Age { get; set; }
[RegularExpression(@"(?i:^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$)")]
public string Email { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment