• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 366
  • Last Modified:

input for text field

Hi experts,

I need code to let the user enter a name into a text field. I want the name to be at least 3 words...also want the text field to accept only letters,spaces and dots and small dash -

thanks
0
Samooramad
Asked:
Samooramad
  • 3
  • 3
  • 2
  • +2
3 Solutions
 
CI-Ia0sCommented:
Hrmmm... that's complicated. You can use JOptionPane to get the input (make sure to put "import javax.swing.*;" at the top of your file):

String nameString = JOptionPane.showInputDialog("Enter a name 3 words long with only letters, periods, spaces, and dashes:");

For making sure it's 3 words at least:

int startPoint = nameString.indexOf(" ");
if (startPoint > -1){
startPoint = nameString.indexOf(" ", (startPoint + 1));
}
else{
//Make them enter it again
}
if (startPoint > -1){
startPoint = nameString.indexOf(" ", (startPoint + 1));
}
else{
//Make them enter it again
}
if (startPoint > -1){
//Do nothing or call a method to proceed
}
else{
//Make them enter it again
}

For making sure it's only letters, spaces, dots, and the dash symbol, do this:
nameString = nameString.toLowerCase();
for (int c = 0; c < nameString.length(); c++){
if (nameString.charAt(c) != 'a' || nameString.charAt(c) != 'b' || nameString.charAt(c) != '.' || nameString.charAt(c) != '-'){
//Make 'em do it again
}

Of course you'll have to have != 'c', d, e, f, etc.
0
 
sudhakar_koundinyaCommented:
// Create a text field with some initial text
    JTextField textfield = new JTextField("Initial Text");
   
    // Create a text field with some initial text and a default number of columns.
    // The number of columns controls the preferred width of the component;
    // each column is rougly the size of an M in the current font.
    int cols = 30;
    textfield = new JTextField("Initial Text", cols);
   
    // Listen for action events, which are fired when the user hits RETURN
    textfield.addActionListener(new MyActionListener());
   
    class MyActionListener implements ActionListener {
        public void actionPerformed(ActionEvent evt) {
            JTextField textfield = (JTextField)evt.getSource();
            if(!valid(textfield.getText()))textfield.setText("");
        }
if (str == null ) {
      return false;
    }
    boolean ok = true;
    for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
        ok = true;
      }
      else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
        ok = true;
      }
      else if (str.charAt(i) == '.' || str.charAt(i) == '-' || str.charAt(i) == ' ') {
        ok=true;
      }
      else {
        ok = false;
        break;
      }
    }
    java.util.StringTokenizer st=new  java.util.StringTokenizer(str);
    if(ok)
    {
      ok = st.countTokens() > 3 ? false : true;
    }

    return ok;
  }
       
    }
0
 
CI-Ia0sCommented:
Yup. That'd be more efficient. I forgot you could use characters as integers... ;)
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
SamooramadAuthor Commented:
thanks CI-Ia0s :)  your help is appretiated

sudhakar can I ask you two questions?
Are the columns meant for sizing the textfield?
what does valid do?
0
 
sudhakar_koundinyaCommented:
columns is to set the length of textField text;
valid checks the text as per your requirements.
if it is not matched return false otherwise true

now based on the text entered , if it is not valid then  just resets the text to null string
0
 
sudhakar_koundinyaCommented:

class MyActionListener implements ActionListener {
        public void actionPerformed(ActionEvent evt) {
            JTextField textfield = (JTextField)evt.getSource();
            if(!valid(textfield.getText()))textfield.setText("");
        }


 public boolean valid(String str) {
    if (str == null) {
      return false;
    }
    boolean ok = true;
    for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
        ok = true;
      }
      else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
        ok = true;
      }
      else if (str.charAt(i) == '.' || str.charAt(i) == '-' ||
               str.charAt(i) == ' ') {
        ok = true;
      }
      else {
        ok = false;
        break;
      }
    }
    java.util.StringTokenizer st = new java.util.StringTokenizer(str);
    if (ok) {
      ok = st.countTokens() > 3 ? false : true;
    }

    return ok;
  }
}

0
 
CEHJCommented:
Try

String s = "Madam I'm Adam";
final String RE1 = "[A-Za-z \\.\\-]+";
final String RE2 = "[^ ]+[ ]+[^ ]+[ ]+[^ ]+";

boolean valid = (s.matches(RE1) && s.matches(RE2));
0
 
objectsCommented:
If you use a custom Document for your text field (subclass PlainDocument) you can stop invalid characters even being entered in the text field removing the need for checking for them.
0
 
objectsCommented:
import javax.swing.text.*;

public class MyDocument extends PlainDocument
{
    public void insertString(int offset, String s, AttributeSet attributeSet)
        throws BadLocationException
    {
        // check for valid characters here
    }
}

0
 
SamooramadAuthor Commented:
ok Im working on it :)
0
 
SamooramadAuthor Commented:
ok sudhakar's and CEHJ's code worked great. I wasn't exactly sure what you meant objects so didnt get that working

thank you
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 3
  • 3
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now