java – Doubts about Regex using Primefaces


I have an input , where when a name is typed in the field, eg João Da Silva , it gives Regex error. In this case, this field must allow upper and lower case letters. Now when I put space it doesn't save.

Here's the code:

<p:outputLabel value="Nome" for="nome" />
<p:inputText id="nome" value="#{cadastroClienteBean.cliente.nome}" size="40" maxlength="50" required="true">
<f:validateRegex pattern="[a-zA-Z]+" />


When creating a regular expression, you need to keep in mind what you want it to match. I learned a lot about this from Aurélio Verde's book Regular Expressions; the regular expression guide is available for free.

I'm going to split the construction of this regular expression into 2 steps:

  1. Match a name without special characters or numbers (ASCII)
  2. Match multiple names

(I'm going to use the nomenclature from Aurélio Verde's regex guide)

To match a name, I need to know what characters can be in the name. In this case, all letters (upper and lower case) at least once. To match the letters, we can use a list that contains these letters: [A-Za-z] . That way I can secure the lyrics. To guarantee a name, a letter needs to appear one or more times, so it needs to be the most , so now it looks like this: [A-Za-z]+

The interpretation that one has when reading this regular expression is: alphabetic characters, in upper or lower case, which appear one or more times. This still doesn't include multiple words.

To include another name, I need to separate the next name from the previous one with a space, and it needs to have 1 or more letters that make up a name. So I can say that the subsequent names are given by the regular expression [A-Za-z]+ (notice the space before the list ). This expression is interpreted as a space followed by a name (as described above). I can use the group followed by an asterisk , as secondary names can appear one or more times. Thus, ( [A-za-z]+)* represents all names after the first name. To put a name before that, we get [A-za-z]+( [A-za-z]+)* .

A weaker check (which allows multiple spaces between names, starts with a space, or consists exclusively of spaces) is [ A-Za-z]+ . The interpretation of this expression is: a string of alphabetic characters, independent of case, and of white spaces.

Scroll to Top