views:

51

answers:

3

I have this regex:

  var alphaExp = /^[a-zA-ZåäöÅÄÖ\s]+$/;

This is for a name-field in a form validation.

I need to make it possible to type names like this "Anna-nicole" (note the minus sign). Currently the minus sign causes error.

I need to remake this regex so that a minus sign can be included in the name, preferrably make it so that the name also CANT start with a minus sign, or end with one. Only minus signs between "words, or names" should be allowed.

Anybody know how to do this?

Btw, it is javascript.

Thanks

+2  A: 

You have to escape the minus sign using backslash.

var alphaExp = /^[a-zA-ZåäöÅÄÖ\s\-]+$/;

To stop them from using it in the beginning or the end, try something like this:

var alphaExp = /^[a-zA-ZåäöÅÄÖ\s]+[a-zA-ZåäöÅÄÖ\s\-]*[a-zA-ZåäöÅÄÖ\s]+$/;
Emil H
Will this stop them from using minus-sign in beginning or end of the field?
Camran
+1  A: 
/^[a-zA-ZåäöÅÄÖ\s]+[a-zA-ZåäöÅÄÖ\s\-]*[a-zA-ZåäöÅÄÖ\s\]+$/ 

should do it (there being a nasty edge case of a single character name, which this won't match. Is a single character name allowed or not?)

Paul
+2  A: 

In a character class, a plain hyphen/minus needs to be first or last:

/^[-a-zA-ZåäöÅÄÖ\s]+$/
/^[a-zA-ZåäöÅÄÖ\s-]+$/

Negated character classes:

/^[^-a-zA-ZåäöÅÄÖ\s]+$/
/^[^a-zA-ZåäöÅÄÖ\s-]+$/

With close square bracket too, put the square bracket at the front and the hyphen at the end:

/^[]a-zA-ZåäöÅÄÖ\s-]+$/
Jonathan Leffler
Thanks Jonathan, but should I combine all these? Dont really know what they all mean, just tell me which one to chose please :)
Camran
@Camran: Choose the one you need - which is probably either of the first two. The second two deal with a negated character class, where the first character after the '`[`' is '`^`'. The last is even more esoteric. However, they don't any of them deal with the more complex issues of ensuring that dash only appears between words, not associated with spaces, etc. I'm half-tempted to delete the answer - but the information about where to place dashes in character classes in regular expressions is still useful (I hope), even though it doesn't address the bigger (and much more) complex issues.
Jonathan Leffler