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; }
}