Yes, it is possible. It's an old question but googling got me here and I'll leave an answer for future readers.
If you're outside ASP you need to invoke the validators yourself. This is how you can do it:
using System;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
class AttributePlayground
{
private string _stringLengthTest;
private int _age;
[StringLength(5)]
public string StringLengthTest
{
get { return _stringLengthTest; }
set { _stringLengthTest = value; ValidateProperty("StringLengthTest"); }
}
[Range(10, 20)]
public int Age
{
get { return _age; }
set { _age = value; ValidateProperty("Age"); }
}
private void ValidateProperty(string propName)
{
PropertyInfo propInfo = this.GetType().GetProperty(propName);
object[] attributes = propInfo.GetCustomAttributes(true);
foreach (object attribute in attributes)
{
ValidationAttribute vattr = attribute as ValidationAttribute;
if (vattr != null)
{
object propValue = propInfo.GetValue(this, null);
vattr.Validate(propValue, propInfo.Name);
}
}
}
}
This yields a nice ValidationException whenever the attribute restrictions are hit during property assignment. If you wanted you could make the validation method static and pass this
as parameter, which allows to keep it in a central place.
See also this question for how to validate manually with the DataAnnotations.Validator class.
It's not within the scope of the question, but it's also possible to use custom attributes. Here's a short example to restrict inputs to a string with fixed length:
// Introduce the [StringLengthIs(number)] attribute:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple=false)]
sealed public class StringLengthIsAttribute : ValidationAttribute
{
public int Length { get; private set; }
public StringLengthIsAttribute(int length)
{
ErrorMessage = "The field {0} must be a string with a length of {1}.";
Length = length;
}
public override bool IsValid(object value)
{
if (value == null) return false;
return value.ToString().Length == Length;
}
public override string FormatErrorMessage(string name)
{
return string.Format(CultureInfo.CurrentCulture,
ErrorMessageString, name, Length);
}
}