views:

88

answers:

4

When I test my javascript at this site it behaves as I would expect.

However when I try and test it on my page it ALWAYS fails the test

function testName() {
    if (new RegExp('^(?!^(\..+)?$)[^\x00-\x1f\\?*:^&!`~@#$$+=<>\?\*;|/]+$').test("me")) {
        alert("good");
    }
    else {
        alert("invalid characters");
    } return false;          
}

The expression is supposed to test a file name for special characters like ^&*!~+=<>` etc. Am I missing something stupid?

+1  A: 

Not wanting to parse your huge ugly RE, I can see one of two problems:

  1. Your test is backwards. The test() call will return false in your example above, meaning that it didn't match any bad characters in "me", so you will get an alert saying "invalid characters", which is backwards.

  2. Your syntax for the test is wrong. Try using a regex literal instead:

    if (/^(?!^(\..+)?$)[^\x00-\x1f\\?*:^&!`~@#$$+=<>\?\*;|/]+$/.test("me")) {
    
Warren Young
Sorry I should have been more specific about what I've done to this point.I originally had the regex literal but moved it to a RegExp so I could make sure it wasn't an invalid expression. Also I think you may be backwards on the test returning false part, given this expression.
Marcus King
Yes, my alternatives are either-or, not both. I could have told you which one if I were willing to try and figure out what that RE means, but as I said, I'm not willing. :)
Warren Young
+5  A: 

When you put your regex into a string (like when you use "new RegEx()" instead of /.../ notation), the regex string has to change. Why? Because it's going to be parsed twice now instead of once: first, as a string - which means all the normal backslash processing that happens inside string constants will take place, and second, as a regex.

Pointy
A: 

Once I closed my browser and cleared the cache, my original expression ended up working, which is good because like Warren young said the substitute expression was ugly.

if(/^[\w-. ()\']+$/.test(this.form.mediaFile.value)) return true; 
else return false;
Marcus King
+1  A: 

Aside from the escaping issue, lookahead assertions (your (?! group) are simply broken in IE (and weren't in the original JavaScript spec). They should not be used in client-side JavaScript. Instead, break the tests in that clause out into separate if conditions.

(If this is a filename tester, you shouldn't rely on it for security as there are many broken constructs it does not catch.)

bobince