How can I not allow the user to type numbers and only text in Java?

Asked

Viewed 6,153 times

5

I am creating a program about registration in which the user has to put name, password, email, etc. But in the fields such as name I want the user can only put text instead of numbers,and that if he puts a number appears a message to say that he can not put numbers but only type in text. How is it possible to do this ? With a method that checks the length of the field ? If you can help me, I’d appreciate it,.

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 : "));
  • 4

    Java web or desktop?

  • 4

    Put the code, always.

  • 3

    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.

  • 1

    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

  • Yes the program is using Joptionpane

  • So it’s Java desktop.

Show 1 more comment

2 answers

7


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.

  1. 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.

  2. 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.

  • Our, thank you so much for having passed this content,helped me a lot. I was just looking for this,I had already seen something about,but not so well explained, anyway,.

  • Only it gave an error when I went to put a part you explained,da this error : "Cannot make a Static Reference to a non method matchesOnlyText(String) from the type Register."

  • You must be trying to access a non-static method from within the main method that is Static, for this to be possible you must put the Static modifier in the matchesOnlyText method OR access it through a Register reference (new Register());

  • I am placing the if code inside the main method,and the matchesOnlyText method outside the main.

  • So as I said you have two options put the Static modifier in the matchesOnlyText method, getting "public Static Boolean matchesOnlyText()" OR before trying to use the method create a class reference variable and accessor through it, for example c = new Registration and then c.matchesOnlyText(). If the answer helped you mark it as the best answer. Thank you.

  • I have already marked friend as best response, thank you very much for the help. Hugs.

Show 1 more comment

3

You can monitor what the user is typing through the "Keytyped" event of a jTexfField and there make the proper treatments as example below:

private void tfNomeUsuarioKeyTyped(java.awt.event.KeyEvent evt) {
//Na variável "c" armazenamos o que o usuário digitou    
char c=evt.getKeyChar();

//Aqui verificamos se o que foi digitado é um número, um backspace ou um delete. Se for, consumimos o evento, ou seja, o jTextField não receberá o valor digitado
if((Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE) || c==KeyEvent.VK_DELETE)){
        evt.consume();
    }                
}
  • I tried to use this your code,and it worked the if part,but in the tfNomeUsuarioKeyTyped it gives an error.

  • This error appears : "Vod is an invalid type for the variable tfNomeUsuarioKeyTyped.'

  • 1

    To use the example code you need to have a jForm and add a jTextField with the name "tfNomeUsuario". Only then you can have an event called "tfNomeUsuarioKeyTyped".

  • Okay, thank you so much for the explanation and for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.