views:

107

answers:

2

I'm using the Validation Application Block from Microsoft. I have a string property which holds a phone number. I have a RegexValidator on it which works pretty well for ensuring only phone number type strings are in the property, but the property should also allow values that are null or an empty string.

Currently the this validator will fail when the value is null or empty.

How can I get around this?

(I know this regex is a tad difficult to read in this format so I supplied a link to test it at.)

    // the regex below can be found and tested at: http://regexlib.com/RETester.aspx?regexp_id=536
    [RegexValidator(@"^(?:(?<1>[(])?(?<AreaCode>[2-9]\d{2})(?(1)[)])(?(1)(?<2>[ ])|(?:(?<3>[-])|(?<4>[ ])))?)?(?<Prefix>[1-9]\d{2})(?(AreaCode)(?:(?(1)(?(2)[- ]|[-]?))|(?(3)[-])|(?(4)[- ]))|[- ]?)(?<Suffix>\d{4})$", MessageTemplateResourceName = "InvalidPhoneNumberMessage", MessageTemplateResourceType = typeof(Xltech.Common.Resources.XLStrings))]
    public string NotificationCellNumber {get; set;}
+2  A: 

You could try adding this to the beginning of the expression:

^$|

It should match the empty string or any regex that follows the | ...

Byron Whitlock
thanks, worked perfectly
Sailing Judo
A: 

This is just a hunch (and I can't test at the moment because I don't have access to the Validation Application Block), but you could try making the entire regex optional by wrapping it with (?: at the beginning and )? at the end:

[RegexValidator(@"^(?:(?:(?<1>[(])?(?<AreaCode>[2-9]\d{2})(?(1)[)])(?(1)(?<2>[ ])|(?:(?<3>[-])|(?<4>[ ])))?)?(?<Prefix>[1-9]\d{2})(?(AreaCode)(?:(?(1)(?(2)[- ]|[-]?))|(?(3)[-])|(?(4)[- ]))|[- ]?)(?<Suffix>\d{4}))?$", MessageTemplateResourceName = "InvalidPhoneNumberMessage", MessageTemplateResourceType = typeof(Xltech.Common.Resources.XLStrings))]
public string NotificationCellNumber { get; set; }
LukeH