views:

756

answers:

3

I'm trying to create a regex that will match only when the string has anything but alphas, spaces, and hyphens. In other words, the string can only contain letters, spaces, and hyphens.

A: 
if(someString.match(/[a-z -]+/i){
    // it's valid
}
inkedmn
"the string can only contain letters, spaces, and hyphens."
inkedmn
change regexp to this: /[^a-z \-]+/i
Eimantas
Eimantas - there's no need to change the regex
inkedmn
If you don't anchor your expression with ^ and $, this will simply match a substring. The rest of the string can still contain unwanted characters.
Ates Goral
Ah, yes, you're right. Silly me :)
inkedmn
A: 

I figured it out and this works perfectly: [^-a-zA-Z\s]

Kyle Hayes
Well, it won't. See gnarf's answer.
Residuum
Why doesn't this one work?
Kyle Hayes
It works - its basically the same as the second part of my answer. It tests the failure case.
gnarf
Ok, which is correct. I need it to test the failure case. Sorry if I wasn't clear about that.
Kyle Hayes
+5  A: 

If you are looking for a test for validity:

// from string start to end, only contains '-' "whitespace" or 'a'-'z' 
someString.match(/^[-\sa-zA-Z]+$/)

Or the negation:

// has some invalid character not '-' "whitespace" or 'a'-'z'
someString.match(/[^-\sa-zA-Z]/)
gnarf
Most comprehensive answer. +1
Ates Goral