0

Been awhile since I needed to do this and I'm just not seeing what the problem is - maybe I'm just burned out too much right now.

var url = '/some-test.php?t=a-t!est&f=&c=4564646&u=4546&ds=45646&de=1254';

if( /^[a-zA-Z0-9\/\-\.\?\=\&]/i.test(url) ) {
    console.log('true');
} else {
    console.log('false');
}

Why is this passing true with 't!est' in the string?

My goal here is to make sure the string is only comprised of :

a-z
A-Z
0-9
/
-
.
?
=
&
case insensitive

I just want to do a quick and simple validation of url (or anything else) before using it... making sure it is only comprised of the characters I specify.

1 Answer 1

1

You are only matching a single character from your character class. As written, the regex is only matching (successfully) the first / and parsing no further. Add a + or * to the end of character class to match multiple characters in test string. Finally, add $ to the end of the regex to anchor to end of line and ensure matches match the entire line.

/^[a-zA-Z0-9\/\-\.\?\=\&]+$/

Or

/^[a-zA-Z0-9\/\-\.\?\=\&]*$/

Sign up to request clarification or add additional context in comments.

2 Comments

Yep... tired. I copied the expression over from using url.match(). Thanks.
/^[a-z0-9\/\-\.\?\=\&]+$/i.test(url) - $ is needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.