lunes, 13 de julio de 2015

Class Custom Validators & Data Annotations

EXAMPLE 1:
using System.ComponentModel.DataAnnotations;

public class Book {
    [CustomValidation(typeof(Book), "ValidateContact")]
    public Contact PrimaryContact { get; set; }

    [CustomValidation(typeof(Book), "ValidateContact")]
    public Contact SecondaryContact { get; set; }

    [Required(ErrorMessage = "Book name is required")]
    public string Name { get; set; }

    public static ValidationResult ValidateContact(Contact contact, ValidationContext context) {
        ValidationResult result = null;

        if (contact == null) {
            result = new ValidationResult(string.Format("{0} is required.", context.DisplayName));
        } else if (string.IsNullOrWhiteSpace(contact.Name)) {
            result = new ValidationResult(string.Format("{0} name is required.", context.DisplayName));
        }

        return result;
    }
}

public class Contact {
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }
}
EXAMPLE 2:
public IEnumerable<ValidationResult> Validate()
{
   return Validate(new ValidationContext(this));
}

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
   var results = new List<ValidationResult>();
   Validator.TryValidateObject(this, validationContext, results, true);
   return results;
}
EXAMPLE 3:
NO CUSTOMIZED:

[RegularExpression(@"^.{5,}$", ErrorMessage = "Minimum 3 characters required")]
[Required(ErrorMessage = "Required")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Invalid")]
CUSTOMIZED:

public class MyStringLengthAttribute : StringLengthAttribute
{
    public MyStringLengthAttribute(int maximumLength)
        : base(maximumLength)
    {
    }

    public override bool IsValid(object value)
    {
        string val = Convert.ToString(value);
        if (val.Length < base.MinimumLength)
            base.ErrorMessage = "Minimum length should be 3";
        if (val.Length > base.MaximumLength)
            base.ErrorMessage = "Maximum length should be 6";
        return base.IsValid(value);
    }
}

public class MyViewModel
{
    [MyStringLength(6, MinimumLength = 3)]
    public String MyProperty { get; set; }
}

Validation Error Message From Data Annotation

CODE EXAMPLE:
[
AttributeUsage(AttributeTargets.Method)] [Match(Regex("dsfasd"))] [StringLength(40, MinimumLength = 1)] [MetadataType(typeof(CustomerMetadata))] [Required()] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] [CustomAttribute(parm1, ErrorMessage = "{0} field validation failed.")] [PhoneMask("999-999-9999", ErrorMessage = "{0} value does not match the mask {1}.")] [DisplayName(@"Do Not Order")] [DefaultValue(0d)] [Range(0.00, 100000000.00, ErrorMessage = "Price must be greater than 0.00.")] [Required(AllowEmptyStrings = false, ErrorMessage = "The {0} is requiered.")] [Min(1, ErrorMessage = "{0} should be minimun of {1}.")] [Column] [DataAnnotationsExtensions.Integer(ErrorMessage = "Please enter a valid number.")] [Mapping(ColumnName = "InventoryId")]
FULL EXAMPLE:

using System.ComponentModel.DataAnnotations;


public class Movie
{
    public int ID { get; set; }
 
    [Required(ErrorMessage = "Title is required")]
    public string Title { get; set; }
 
    [Required(ErrorMessage = "Date is required")]
    [DisplayFormat(DataFormatString = "{0:d}")]    ---->   alternatively,     [DataType(DataType.Date)] 
    public DateTime ReleaseDate { get; set; }
 
    [Required(ErrorMessage = "Genre must be specified")]
    public string Genre { get; set; }
 
    [Required(ErrorMessage = "Price Required")]
    [Range(1, 100, ErrorMessage = "Price must be between $1 and $100")]
    [DisplayFormat(DataFormatString = "{0:c}")]    ---->   alternatively,     [DataType(DataType.Currency)]
    public decimal Price { get; set; }
 
    [StringLength(100)]
    [Required(ErrorMessage="Required")]
    [Display(Description = "First Name")]
    [RegularExpression(@"^([a-zA-Z0-9 \.\&\'\-]+)$", ErrorMessage = "Invalid First Name")] 
    public string Rating { get; set; }
}

source code