Globally deny and make case insensitive

Is there a better way to do this? I can't figure out how to add (?i)

so that I can make the template globally case insensitive while keeping the assertion as negated.

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

      

+3


source to share


2 answers


I tested this and just added that (?i)

to the top (as @sln says) works great 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'm sorry; I've only tried this on the pure-C # end. With MVC model validation as it seems you are doing, you need a Regex expression that works in both C # and JavaScript. By its nature, C # supports (?i)...

to denote case insensitivity, while JavaScript supports /.../i

. But no notation will work in the other. The best you could do is either what you already have (definition p|P

, o|O

etc.), or a custom attribute RegularExpressionWithOptions

like Jeremy Cook in Answer here here .
+3


source


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



-1


source







All Articles