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

5

I am creating a program on register 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 case he put a number to appear a message to speak that he can not put numbers and yes just type in text form. How can this be done? With a method that checks the length of the field? Anyone who can help me thanks, if necessary I 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 : "));
    
asked by anonymous 12.12.2015 / 22:08

2 answers

7

Well, it's simple. By the code that you put and by JOPtionPane I see that you are working with Java SE.

You can create a method to validate if the user input contains text only (for text it means only alphabetic characters) through regex.

Regular Expression (regex) is nothing more than a string that defines a search pattern in Strings, you can create expressions to validate a myriad of patterns, such as emails, cpfs, etc. to know more .

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

  • The first: "[a-zA-Z \ s] +" In this you will only validate lowercase letters (az), uppercase letters ). The + character indicates that this combination can occur 1 or more times. Check out the example applied here http: // regexr.com/3cd9n, as you will realize this expression will not accept special characters or accents and in case you want them to be accepted let me search for it yourself, a link to get started.

  • The second: "[^ \ d] +" This expression is easier if you just do not want to accept numbers and want to accept any other character type. The ^ character is used to deny the character \ d indicating the digits. See the example in practice http: // regexr.com/3cd9q.

  • To apply in Java you only need a String to be able to call the class 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 caracter 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 have helped at least start your regex studies.

    Sorry for the broken links, because I can not publish above 2 links, just take the space. Thanks.

        
    12.12.2015 / 23:36
    3

    You can monitor what the user is typing through the "KeyTyped" event of a jTexfField and there make the appropriate treatments as shown 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();
        }                
    }
    
        
    13.12.2015 / 14:07