I'm trying to get this name validation regex working but am having issues. I have made sure I have the unicode addon for regexp but it does not seem to be working. This regex works with php pcre regex.
XRegExp("^[a-zA-Z\s,.'-\pL]+$").test('á');
The above returns false. I've never used xregexp and haven't been able to find anything online that seems to explain how to do this. Any help would be great, thanks!
This particular regex should accept all unicode characters, dashes, commas, periods, and letters upper and lower.
It is quite easy once you check what your pattern looks like in the console. It looks like /^[a-zA-Zs,.'-pL]+$/
, which means, it does not match Unicode letters at all, as the backslashes are gone (you need to use double backslashes in the string literals to define a literal backslash that escapes special chars in regex). Note that instead of whitespace, you match a literal s
, and '-p
creates a valid range, so there is no error thrown, but the results are really unexpected. Here is what that range matches (yes, including digits):
What you also miss is that \pL
already includes [a-zA-Z]
, so that part in your pattern is redundant.
// YOUR REGEX
console.log("^[a-zA-Z\s,.'\-\pL]+$"); // => /^[a-zA-Zs,.'-pL]+$/
// SHOULD BE DEFINE AS
console.log("^[\\s,.'\\pL-]+$"); // => /^[\s,.'\pL-]+$/
// TEST
console.log(XRegExp("^[\\s,.'\\pL-]+$").test('á')); // => true
<script src="http://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.min.js"></script>