Meaningless Drivel is fun!
The moose likes Java in General and the fly likes String Validations Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "String Validations" Watch "String Validations" New topic

String Validations

dharmesh baveja

Joined: Dec 18, 2000
Posts: 13
I want to do following validations in Swing.JTextField:
1. A string entered in text box should get validated for some special character like @, ' ,* . This has to be done at on the key entering .Backspace should work also.
2. A string entered in text box should have only number digits(0,1,2,3...9) .Backspace and other control character should behave properly. This has to be done at on the key entering .Backspace should work also.
Pls help me out . Please try that code should be generic and small.
Regards & Thanks in advance.
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Try this link to Sun's tutorial.

"I'm not back." - Bill Harding, Twister
Mazhar Shaikh

Joined: May 14, 2001
Posts: 5
Hi there,
u need to use following lines of code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
//converts every alphabets to its upper case and allows only alphabets+Numbers
class AlphaNumTextField extends JTextField
public AlphaNumTextField(int cols)
protected Document createDefaultModel()
return new AlphaNumDocument();
static class AlphaNumDocument extends PlainDocument
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException
if (str == null)
char[] upper = str.toCharArray();
boolean flag=false;
for (int i = 0; i < upper.length; i++)
upper[i] = Character.toUpperCase(upper[i]);
if (upper[i]=='\n')
System.out.println("***char= enter");
if (Character.isLetter(upper[i])| |Character.isDigit(upper[i])) flag=false;
else flag=true;
if (flag==false)
super.insertString(offs, new String(upper), a);
I hope this might solve your problem.U just need to do certain changes in the above for loop.
Thats it
I agree. Here's the link:
subject: String Validations
It's not a secret anymore!