?
Solved

number validation in Java

Posted on 2003-03-15
7
Medium Priority
?
5,287 Views
Last Modified: 2012-06-27
How can I check the validation of numbers in TextField,I mean that the users must be able to enter numbers only (like 30,3000,56.76,....), so it must show a message box if any other character that is not a number is entered.
0
Comment
Question by:urmila
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 9

Accepted Solution

by:
yongsing earned 1000 total points
ID: 8141928
Use the Double.parseDouble() method to validate the text is a floating point number, or use Integer.parseInt() if you want it to be an integer.

textField.addActionListener(
 new ActionListener() {
   public void actionPerformed(ActionEvent actionEvent) {
     TextField tf = (TextField)actionEvent.getSource();
     String text = tf.getText();
     try {
        double number = Double.parseDouble(text);
     } catch (NumberFormatException e) {
        // Show error message here.
        return;
     }
     // String is ok. Do what you want with it here.
   }
 }
);
0
 
LVL 1

Expert Comment

by:Piter
ID: 8142034
If you are using JSP or servlets.
 Make one validation.js file and on Submit button check validation for each check box.
 if you want i can give you the code. its little bit leangthy but it will check for each char entered in that text box.


reply,

piter
0
 
LVL 1

Expert Comment

by:umangjoshi
ID: 8142247
Pls use javax.swing.JFormattedTextField
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!

 
LVL 86

Expert Comment

by:CEHJ
ID: 8142268
If you are not using Swing, you'll have to add a KeyListener to the field that restricts entry. Better is to use Swing and call

jTextField.setDocument(new DecimalDocument(2));// for two decimal places

with something like the class below:

class DecimalDocument extends PlainDocument {
  int decimalPlaces;
  int pointPosition;
  boolean badChars;
  StringBuffer buffer;

  public DecimalDocument(int decimalPlaces) {
    super();
    this.decimalPlaces = decimalPlaces;
    pointPosition = -1;
    buffer = new StringBuffer();
  }

  public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {

    try {
      buffer.append(getText(0, getLength())).append(str);
      for(int i = 0; i < buffer.length(); i++) {
        if (!(Character.isDigit(buffer.charAt(i)) || buffer.charAt(i) == '.')) {
          badChars = true;
        }
        if (buffer.charAt(i) == '.') {
          if (pointPosition == -1) {
            pointPosition = i;
          }
          else {
            badChars = true;
          }
        }
      }
      // Now validate decimal places
    }
    finally {
      if (!badChars) {
        if (pointPosition < 0) {
          super.insertString(offs, str, a);
        }
        else {
          if ((buffer.length() - 1 - pointPosition) <= decimalPlaces) {
            super.insertString(offs, str, a);
          }
        }
      }
      reset();
    }
    try {
      Integer.parseInt(str);
    }
    catch(NumberFormatException e){
      //e.printStackTrace();
      return;
    }
    // str is an integer
    if (getLength() + str.length() <= decimalPlaces) {
      super.insertString(offs, str, a);
    }

  }

  void reset() {
    pointPosition = -1;
    badChars = false;
    buffer.setLength(0);
  }
}


0
 

Author Comment

by:urmila
ID: 8145895
Yes,it's working
Thank u
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8146243
That won't stop anything other than numbers being entered, as your question specified:

>>I mean that the users must be able to enter numbers only
0
 
LVL 9

Expert Comment

by:yongsing
ID: 8149162
If he is using a TextField, there's nothing much he can do to prevent the user from entering numbers only. Adding a key listener won't help much because the user can still do a copy & paste (of non-number characters) onto the TextField.
0

Featured Post

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!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month9 days, 12 hours left to enroll

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question