ng-pattern for PCRE

112 Views Asked by At

I have this pattern for an input text field: /[\p{L}\'.\- ]{3,30}/ My intention is to accept the most broadly names of people on several alphabets of the world (Latin, Cyrillic, Chinese, etc.) It was tested in Regex101 and it works great. On other testers it doesn't work but my main issue comes as follows:

<form action="mailto:[email protected]" id="formula" method="post" enctype="multipart/form-data" 
name="formname" class="form-group pt-3" autocomplete="on" ng-submit="register()" novalidate>
<input type="text" name="nombre" ng-pattern="/[\p{L}\'.\- ]{3,30}/">

Here's my code for you to check: https://regex101.com/r/gOvO2M/8 It skips special characters, skips symbols, skips numbers, but when I see the live HTML in the browser, it doesn’t work properly.

In the error message, for validation purposes, I put:

<p class="formu-error" ng-show="formname.nombre.$touched && formname.nombre.$invalid">Please, write a valid name.</p>

The problem is when testing, I write only letters (no spaces, no hyphen because all that is optional) and still giving me the message of the error. Why?

Maybe because I am using \p{L} and that will work only in the server, when I code the server validation in PHP?

1

There are 1 best solutions below

0
On

You can use

<input type="text" name="nombre" ng-pattern="/^(?=.{3,30}$)\p{L}+(?:['.\s-]\p{L}+)*$/u" ng-trim="false" />

Note the u flag, it enables the Unicode category (property) classes support in JavaScript with the ECMAScript 2018+ support.

Also, ng-trim="false" will prevent trimming whitespace before passing the input to the regex engine.

The regex means:

  • ^ - start of string
  • (?=.{3,30}$) - the string must consist of 3 to 30 chars other than line break chars
  • \p{L}+ - one or more Unicode letters
  • (?:['.\s-]\p{L}+)* - zero or more repetitions of
    • ['.\s-] - a ', ., whitespace or -
    • \p{L}+ - one or more Unicode letters
  • $ - end of string.

See the regex demo.