Including a hyphen in a regex character bracket?

ParoX picture ParoX · Sep 13, 2010 · Viewed 108.7k times · Source
$.validator.addMethod('AZ09_', function (value) { 
    return /^[a-zA-Z0-9.-_]+$/.test(value); 
}, 'Only letters, numbers, and _-. are allowed');

When I use somehting like test-123 it still triggers as if the hyphen is invalid. I tried \- and --

Answer

Mark Byers picture Mark Byers · Sep 13, 2010

Escaping using \- should be fine, but you can also try putting it at the beginning or the end of the character class. This should work for you:

/^[a-zA-Z0-9._-]+$/