Ok so when I want to have a property be validated, I might write something like this:
[Required]
[StringLength(255)]
[DataType(DataType.EmailAddress)]
[RegularExpression(RegexStrings.Email, ErrorMessage = "Email is not valid.")]
[DataMember(IsRequired = true, Name="Email", Order = 1)]
public string Email { get; set; }
I like this because in this case, I point it to the regex strings that we have in our common library and specify an error message if it fails. Simple and clean.
My situation is this. This is in a WCF RESTful service. One of the properties that I want validated in this fashion needs to be validated using a custom method which validates using some business logic (it checks the string length and byte length). Can I (and how do i) set up this custom validation so that I can use it like it used in the above example; so it looks something like:
[StreamValidation(ValidationClass, ErrorMessage = "Serial number is invalid")]
public string Ksn { get; set; }
UPDATE:
I have constructed the following class to be my attribute:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class KsnValidation : ValidationAttribute
{
public override bool IsValid(object value)
{
if (!(value is string)) return false;
var val = (string) value;
var bytes = Enumerable
.Range(0, val.Length / 2)
.Select(x => Byte.Parse(val.Substring(2 * x, 2), NumberStyles.HexNumber))
.ToArray();
return val.Length == 20 && bytes.Length == 10;
}
public override string FormatErrorMessage(string name)
{
return base.FormatErrorMessage(name);
}
}
Then decorated the following property:
[KsnValidation(ErrorMessage = "Wrong Name")]
public string Ksn { get; set; }
But I'm not sure how to unit test this