Rough
Rough

Reputation: 366

Creating regex for javascript

I am keen on using both [^\u0000-\u007F]+ and ^[A-Za-z0-9._-](?:[A-Za-z0-9._ -]*[A-Za-z0-9._-])?$ as a one regex but it's so complicated, I just couldn't make it work? Any ideas how to integrate both?

I want to use JavaScript version for client-side verification and Php version for server-side verification.

Upvotes: 1

Views: 491

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

I suggest using the remaining part of the Unicode table with [\u0080-\uFFFF] instead of [^\u0000-\u007F].

In JS, \w matches [A-Za-z0-9_], I suggest using

^[\u0080-\uFFFF\w.-](?:[\u0080-\uFFFF\w. -]*[\u0080-\uFFFF\w.-])?$

See demo

In PHP, just use \p{L} with /u modifier:

$re = '/^[\p{L}0-9_.-](?:[\p{L}0-9_. -]*[\p{L}0-9_.-])?$/u'; 
          ^^^^^           ^^^^^          ^^^^^           ^

It looks like no one likes \uXXXX in PHP. @nhahtdh confirms there may be issues with matching same code points.

Upvotes: 2

Related Questions