Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a simple example. suppose you have an object like the following</p> <pre><code>using System.ComponentModel.DataAnnotations; public class Contact { [Required(AllowEmptyStrings = false, ErrorMessage = "First name is required")] [StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")] public string FirstName { get; set; } public string LastName { get; set; } [DataType(DataType.DateTime)] public DateTime Birthday { get; set; } } </code></pre> <p>And suppose we have a method that creates an instance of this class and tries to validate its properties, as listed below</p> <pre><code> private void DoSomething() { Contact contact = new Contact { FirstName = "Armin", LastName = "Zia", Birthday = new DateTime(1988, 04, 20) }; ValidationContext context = new ValidationContext(contact, null, null); IList&lt;ValidationResult&gt; errors = new List&lt;ValidationResult&gt;(); if (!Validator.TryValidateObject(contact, context, errors,true)) { foreach (ValidationResult result in errors) MessageBox.Show(result.ErrorMessage); } else MessageBox.Show("Validated"); } </code></pre> <p>The DataAnnotations namespace is not tied to the MVC framework so you can use it in different types of applications. the code snippet above returns true, try to update the property values to get validation errors.</p> <p>And make sure to checkout the reference on MSDN: <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx" rel="noreferrer">DataAnnotations Namespace</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload