3

My application includes creating POCO classes at runtime using the CodeDOM. I am looking for a way to allow my end user to specify a limitation on the value of some properties he creates (e.g. if he adds a property Email than he would probably like to validate the content to an email address. It is obvious that the end user might have more custom restrictions).

My intention is to offer a PropertyValidation field where the end user can provide a regular expression which serve as a validator for the content of created instances of that property.

Is there any way I can make sure the string provided in the PropertyValidation field is an actual Regex before allowing it?

Moslem Ben Dhaou
  • 6,897
  • 8
  • 62
  • 93
  • 2
    Use a `Try...Catch` block http://stackoverflow.com/questions/218680/can-i-test-if-a-regex-is-valid-in-c-sharp-without-throwing-exception – keyboardP Jul 30 '13 at 12:23
  • Do your end users know how to write regular expressions correctly? Keep in mind that a simple `hi` is a valid regex, but might not do what the end user wants. Also, some stuff (ie. mail addresses or even HTML input) cannot be validated through regexes easily. Additionally, badly written and frequently regular expressions can make an application slow. – hangy Jul 30 '13 at 12:25
  • 1
    What do you mean **valid**? This, `.`, is a valid Regex. – Mike Perrenoud Jul 30 '13 at 12:25
  • 1
    @TheSolution Yes, but this is not: `?` – Lasse V. Karlsen Jul 30 '13 at 12:32
  • @hangy: My end users are system administrators so yes they know how to right a regular expression – Moslem Ben Dhaou Jul 30 '13 at 12:37
  • @TheSolution: I don't really care as long as they wrote it. – Moslem Ben Dhaou Jul 30 '13 at 12:38

2 Answers2

7

Try to create a Regex object and catch any resulting errors:

try { Regex reg = new Regex(userDefinedValidation); } 
catch (ArgumentException) { /* not a regex */ }
Brian Stephens
  • 5,161
  • 19
  • 25
-3

if the "Try-Catch way" is too general, then you should, for example, write a regex that parses correct regexes ;)

eivan
  • 5
  • 1