Search code examples
.netvisual-studiovalidation.net-2.0

How do I indicate a validation requirement to users of my class?


I'm implementing a class that wraps around an xml document with a very strictly defined schema. I don't control the schema.

One of the properties in the class is for an element value that the schema indicates must match a certain regular expression. In the setter for the property, if a string doesn't match the expression I'm throwing an exception.

My question is, how can I better communicate to users of my class the requirements for this field? Is there an attribute I can use? Xml comments (so it shows up in intellisense)? Should I do something other than thrown an exception? What other options do I have?


Solution

  • Thanks for the advice.

    One idea I had while thinking about this was creating a new class named something like MatchedString to enforce the constraint.

    It'd have a constructor that required a regex string, and after construction the expression would only be exposed to users via a read-only property. Then it would have a value property that users could set that would check against the expression in the setter.

    My thought was that I could then also create options for different behaviors to use when the validation failed in an enum, and let the user specify which they want:

    • set to empty string
    • set to empty string and throw exception
    • set bad value anyway
    • set bad value anyway, and throw excpetion
    • just throw exception
    • do nothing

    Also, I was thinking that this would allow my class user to do some basic tests without having to duplicate the RegEx object in their own code. Throw in implicit conversions to/from the string type, and it should be intuitive to class users.

    Any thoughts on this?