0

I need the variable that will be passed through this function to be tested against the following characters: #"/:*?<>|;^. So far I have this:

if(/^[#"\/:*?<>|;^]*$/.test("test word") == false){
            alert('this includes illegal characters #"\/:*?<>|;^');
}

but even when the variable doesn't include the illegal characters it pops off the alert. Does anyone know what I am doing wrong with my regex?

4
  • 1
    Obviously more characters should b escaped with \ Commented Jan 7, 2014 at 21:26
  • @u_mulder: it's false, the only character you must escape in a character class is the delimiter / and the literal closing square bracket or the literal ^ (if it is at first position in the class). Commented Jan 7, 2014 at 21:31
  • * - zero or more occurrences, remove it and flip your boolean to true. also use === over ==. Commented Jan 7, 2014 at 21:32
  • You only need to remove anchors (^ and $) and the quantifier * Commented Jan 7, 2014 at 21:37

2 Answers 2

2

Your current code is testing to see if your string does NOT consist entirely of illegal characters. That isn't going to give you what you want. What you want to test for is if there are ANY illegal characters. To do that, you can do this:

if(/[#"\/:*?<>|;^]/.test("test word")){
            alert('this includes illegal characters #"\/:*?<>|;^');
}

This removes the ^ and the $ so you can find any illegal characters and it changes the sense of the boolean test. This way, it hits the if statement if ANY illegal character is found anywhere in the string.


FYI, it is generally better to test to see if your string contains ONLY "legal" characters rather than the other way around because this way you might be letting control characters or other things like that through that you haven't thought of.


A test for all legal characters might look like this (you have to fill in the exact legal characters):

if (!/^[a-zA-Z. ]+$/.test("test word")){
     alert('some illegal characters present');
}
Sign up to request clarification or add additional context in comments.

2 Comments

couldn't have said it better myself
@AndrewButler good choice for an answer - though your question is not clear on this, I was guessing you wanted to include the backslash \ as an illegal character. If so, then add an extra \\ to your regex.
1

This should work:

if( /[#"\\\/:\*\?<>\|;\^]/.test("test word") ){
            alert('this includes illegal characters #"\/:*?<>|;^');
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.