Globally negate and make case insensitive

637 views Asked by At

Is there a better way to do this? I cannot figure out how to add (?i) so I can make the pattern globally case insensitive while still keeping the statement as a negation.

[Required(ErrorMessage = "Address")]
[RegularExpression("^(?!.*(p|P)\\.?(o|O)\\.?\\s+?(box|Box|BOX)).*$", ErrorMessage = "We cannot ship to PO boxes")]
public string CustomerAddress1 { get; set; }
2

There are 2 answers

3
Arin On

I tested this out, and simply adding that (?i) to the beginning (as @sln says) works fine for me.

Here's my test code, in a console app:

static void Main(string[] args)
{
    TestForPoBox("PO BOX 111");
    TestForPoBox("P.O. Box 222");
    TestForPoBox("p.O. boX 333");
    TestForPoBox("444 Main Street");

    Console.ReadKey();
}

static void TestForPoBox(string streetAddress)
{            
    const string pattern = "(?i)^(?!.*p\\.?o\\.?\\s+?box).*$";
    Match match = Regex.Match(streetAddress, pattern);

    //Write out the matches
    if (match.Length > 0)
        Console.WriteLine("OK. Address is not a P.O. Box: " + streetAddress);
    else
        Console.WriteLine("INVALID. Address contains a P.O. Box: " + streetAddress);
}

and here's the output:

INVALID. Address contains a P.O. Box: PO BOX 111
INVALID. Address contains a P.O. Box: P.O. Box 222
INVALID. Address contains a P.O. Box: p.O. boX 333
OK. Address is not a P.O. Box: 444 Main Street


EDIT: I apologize; I had only tried this out on the purely-C# end. With MVC model validation like it appears you're doing, you'd need a Regex expression that works in both C# and JavaScript. By nature, C# supports (?i)... to signify case-insensitivity, while JavaScript supports /.../i. But neither notation will work in the other. Best you might be able to do is either what you already have (spelling out p|P, o|O, etc.), or else a custom RegularExpressionWithOptions attribute like Jeremy Cook's in the SO answer here.

1
Blaargon On

You could use the .tolower() method on the string during comparison.