简体   繁体   中英

Preventing a String from getting integer values in Java

Is there a possible way to do that?

eg In my application form a have a field for the user's name which is a String . But how can I disallow the user from giving for example "L3bron James" instead of giving "Lebron James" ?

String sql_name = name.getText();
// name is a JTextField
if (sql_name.length() == 0)
    {
        //how to check if the name does not contain int digits
    JOptionPane.showMessageDialog(null,"Name is a string ,NOT an Integer, not a null value!!","Invalid Name",JOptionPane.ERROR_MESSAGE);
    }

You can use a regular expression on the string to see if it contains number characters:

if (Pattern.compile("[0-9]").matcher(sql_name).find()) {
    // Show error message
}

It depends on where you want to filter for integers. Following this answer How to filter string for unwanted characters using regex? you can use regex to check for integers and prompt the user again if you found an integer. Or you could just replace them which would be kind of rude.

You can use StringUtils.isAlphaSpace from apache commons

StringUtils.isAlphaSpace(null)   = false
StringUtils.isAlphaSpace("")     = true
StringUtils.isAlphaSpace("  ")   = true
StringUtils.isAlphaSpace("abc")  = true
StringUtils.isAlphaSpace("ab c") = true
StringUtils.isAlphaSpace("ab2c") = false
StringUtils.isAlphaSpace("ab-c") = false

Alternative Solution

boolean flag = false;
for (int i = 0; i < sql_name.length(); i++) {
        if (Character.isDigit(sql_name.charAt(i)))
                flag = true;// number exists in the string
            }
if (flag == true)
   JOptionPane.showMessageDialog(null,"Name is a string ,NOT an Integer, NOT a null value!!","Invalid Name",JOptionPane.ERROR_MESSAGE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM