This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Validations

 
dharmesh baveja
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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.
Dharmesh
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this link to Sun's tutorial.
 
Mazhar Shaikh
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
{
super(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)
{
return;
}
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')
{
upper[i]='\t';
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);
else
{
}
}
}
}
---------------------------------------------------------------
I hope this might solve your problem.U just need to do certain changes in the above for loop.
Thats it
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic