How to use validation attributes

Here is a markup of some simple and standard ValidationAttributes.


using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Your.Namespace
{
    public class YourModel
    {
        // Normal required field, with static Errormessage if validation fails.
        [Required(ErrorMessage = "Id is required")]
        public int Id { get; set; }

        // Required field with multilangual response if validation fails. 
        // In this case your language file is named language.TwoLetterISOLanguageName.resx, 
        // and the Name of the index is field_empty.
        [Required(ErrorMessageResourceType = typeof(Resources.language), ErrorMessageResourceName = "field_empty", ErrorMessage = null)]
        public string MultilangualField { get; set; }

        // Validation of a email, with response if validation fails.
        [EmailAddress(ErrorMessage = "Invalid email")]
        public string Email { get; set; }

        // This property has to be the same as Email.
        [Compare("Email", ErrorMessage = "Emails do not match.")]
        public string RepeatEmail { get; set; }

        // Display name of the property in the view.
        [Display(Name = "Your Name")]
        public string Name { get; set; }

        // Errormessage if there is more then 255 charecters. You can set a minimum on it too.
        // or add a Required attribute.
        [StringLength(maximumLength: 255, ErrorMessage = "Max 255 charecters")]
        public string Max { get; set; }

        // Password property.
        [DataType(DataType.Password)]
        public string Password { get; set; }

        // A complete Email property would look like this.
        [Display(Name = "Email", Description = "Enter your own email.")]
        [StringLength(maximumLength: 255, MinimumLength = 7, ErrorMessage = "Max 255 charecters and minimum 7.")]
        [Required(ErrorMessage = "Your email is required.")]
        [EmailAddress(ErrorMessage = "Invalid email")]
        public string CompleteEmail { get; set; }
    }
}