Question

I'm trying to use conditionals in RegularExpression attribute to validate particular set of formats for a property, but it seems that as soon as I include it (conditional) in the pattern anything passes validation.

I tried even the simplest ones, and also examples from Microsoft (like this one: @"\b(?(\d{2}-)\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b" but nothing seems to work (all values are allowed).

Added for clarity: I need to validate tax registration number. Rules are:

if it starts with country identifier 
   for country CC do strict format check
   for all other countries allow any string
else 
  assume it's local number and do strict format check

(most of the time registration will be local and rules are known, but it should be possible to enter foreign number with unknown format).

While certainly I would be grateful for a regex allowing above, my question is not about the particular pattern itself, but rather why using conditional - in this particular scenario (asp.net/c# attribute) - in the pattern trips off validation and how to resolve it.

Was it helpful?

Solution 2

I was missing the obvious (thanks Robin for pointing me towards implementation)

Here is what happened :)
I checked if .net supports conditionals (it does)
I put a conditional into Regex attribute and it was happily parsed and compiled.

I then tried to check if it works by firing web form and entering gibberish. It should produce warning message about incorrect format when the input lost focus. It did not.

What I forgot is that this 'instant' client side validation (mvc unobtrusive validation) is actually done via jquery/javascript code generated and embedded by mvc templating engine.

This means it was actually javascript matching those patterns. Unfortunately javascript does not support conditionals so as soon as it saw one it went meh

OTHER TIPS

The syntax for a condititional statement is (?(?=condition)iftrue|else), so your regex should probably be

\b(?(?=\d{2}-)\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b

But it seems to me you don't need condition in this example, remember the (?=...) is zero width (and here the conditions are mutually exclusive).This should be enough:

\b(?:\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top