2

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

Sinaesthetic
  • 11,426
  • 28
  • 107
  • 176

2 Answers2

3

This SO answer givens an answer for MVC2.

And here is a post for MVC3 and up.

Basically you create an Attribute:

public class MyValidationAttribute: ValidationAttribute
{
   public MyValidationAttribute()
   { }

    protected override ValidationResult IsValid(
           object value, ValidationContext validationContext)
    {

        ...
        if (somethingWrong)
        {
            return new ValidationResult(errorMessage); 
        }
        return null; // everything OK
    }
}
Community
  • 1
  • 1
H H
  • 263,252
  • 30
  • 330
  • 514
  • A quick test would be entering wrong number on the screen. I'm not sure how to Unit test, you need to Attach the entity to a context I think. – H H Oct 26 '12 at 19:12
  • I ran my service and sent in bad data, but it never threw an error :/ – Sinaesthetic Oct 26 '12 at 20:12
  • I found out that apparently, running validation on the object does not do so for it's child members. Rather, it only validates the first level :/ – Sinaesthetic Oct 29 '12 at 00:35
0

The documentation for ValidationAttribute shows how to create your custom validation attribute.

fsimonazzi
  • 2,975
  • 15
  • 13