How to disallow the user to type numbers and only text in Java?

Question:

I'm creating a program about registration in which the user has to put name, password, e-mail, etc. But in the fields such as name I want the user to only be able to put text instead of numbers, and that if he puts a number appears a message to say that he cannot put numbers but only type in text form. How is it possible to do this? With a method that checks the length of the field ? Who can help me I appreciate it, if necessary I'll put the code.

Here is the code:

String nome,email;
double password,account; 

nome = JOptionPane.showInputDialog("Qual seu nome ? ");
email = JOptionPane.showInputDialog("Qual seu email ?");
account = Double.parseDouble(JOptionPane.showInputDialog("Digite uma account : "));
password = Double.parseDouble(JOptionPane.showInputDialog("Digite um password : "));

Answer:

Well, it's simple. From the code you posted and from the JOPtionPane I can see that you are working with Java SE.

You can create a method to validate that user input contains only text (by text we mean only alphabetic characters) through regex.

Regular Expression (regex) is nothing more than a sequence of characters that define a search pattern in Strings, you can create expressions to validate a multitude of patterns, such as emails, website addresses, cpfs, etc. to learn more .

I'm going to give you two options of expressions to start your studies on the subject and help you reach the goal.

  1. The first one: "[a-zA-Z\s]+" In this one you will only validate lowercase(az), uppercase(AZ) and whitespace(\s). The + character indicates that this combination can occur 1 or more times. Check the example applied here , as you will notice this expression will not accept special characters or accents and if you want them to be accepted I will let you search for yourself, a link to get started.

  2. The second: "[^\d]+" This expression is easier if you just don't want to accept number and want to accept any other type of character. The ^ character is used to negate the \d character that indicates digits. See the example in practice .

To apply it in java you just need a String to be able to call the matches method of the class, see an example of a 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 code example, 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 I've helped, at least to get you started on your regex studies.

Scroll to Top