Well, it’s simple. By the code you put in and by Joptionpane I see that you are working with Java SE.
You can create a method to validate if the user input contains only text (text is only alphabetic characters) through regex.
Regular Expression (regex) is nothing more than a string of characters that define a search pattern in Strings, you can create expressions to validate a multitude of patterns such as emails, web addresses, cpfs, etc.. to learn more.
I will give you two options of expressions to start your studies on the subject and help you achieve the goal.
The first: "[a-za-Z s]+" In this you will validate only lower case letters (a-z), upper case letters (A-Z) and white space ( s). The + character indicates that this combination can occur 1 or more times. Check out the applied example here, as you will notice this expression will not accept special characters or accents and if you want them accepted I will let you search yourself, a link to begin with.
The second: "[^\d]+" This expression is easier if you just don’t want to accept number and want to accept any other character type. The character is used to negate the character d that indicates the digits. See the example in practice.
To apply in java you only need a string to call the class’s Matches method, see an example method:
public boolean matchesOnlyText(String text) {
return text.matches("[^\\d]+"); //Passa para o método matches a regex
//Se tiver número na string irá retornar falso
//Note o uso de duas \\, uma sendo obrigatória para servir de caractere de escape
}
Now according to your own example of code, you can do something like:
String nome = JOptionPane.showInputDialog("Qual seu nome ? ");
if(!matchesOnlyText(nome)) {
JOptionPane.showMessageDialog(null, "Você não pode inserir números no nome.");
}
I hope to have helped, at least to start your studies of regex.
Java web or desktop?
– user28595
Put the code, always.
– Maniero
Hello Falion. Is it a program with Desktop, Console or Web client? What Java technologies are you using? What have you done? Please post a piece of relevant code indicating exactly which field you would like to validate.
– Anthony Accioly
Out of curiosity, is your program using Joptionpane to create your program? What you want, has to be done in a JPANEL with Jtextfield’s, Jlabel’s and etc. See this example of a swing form
– user28595
Yes the program is using Joptionpane
– Falion
So it’s Java desktop.
– Falion