Search code examples
javascripthtmlregexsecurityvalidation

Include the hyphen into this regular expression, how?


I have some JavaScript code using a regex, to validate a name field in a form:

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

I want the regex to allow names that include a hyphen, such as Anna-nicole.

Ideally, the regex should reject names that start or end with a hyphen.

How can I modify the regex to make this work? I get an error if I try to add a hyphen to the character class.


Solution

  • 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]+$/;