granadaCoder
granadaCoder

Reputation: 27852

Regex allowing < and >

Can anyone tell me why this regex is allowing < and > ?

function IsValidPassword(password) {
    var regex = /^[A-Za-z0-9^\~^\!@/#^\$^\%&^\*+-_()]*$/; /* AlphaNumerics.  ~ (Tilde) (All "Shifts" 1-0)  underscore plus and minus */
    return regex.test(password);
}

My goal is

Upvotes: 1

Views: 54

Answers (2)

Cameron
Cameron

Reputation: 98746

This is because when you put the second - (intending to check for a literal -), it actually represents the range between + and (, which happens to include < and >.

You simply need to escape the - (note also that your regex can be simplified):

/^[A-Za-z0-9~!@#$%^&*()+\-_]*$/

Upvotes: 1

Marc B
Marc B

Reputation: 360602

/^[A-Za-z0-9^\~^\!@/#^\$^\%&^\*+-_()]*$/
                               ^^^--- plus to underscore

< and > fall within that range:

+   -> ascii(43)
<   -> ascii(60)
>   -> ascii(62)
_   -> ascii(95)

that +-_ range also happens to include the entire uppercase alphabet, so you could remove A-Z from the pattern and it would STILL work.

Upvotes: 7

Related Questions