How to restrict user to enter digits or special charater or blank or space in JTextField in Java Swing? -


i working on project in java swing. there text field user name. want validate text field user can't enter digits or special character or blank or space. in short want restriction such user can't enter other alphabets. database ms access , table name "test" , there 1 column named "sname". beginner, simpler techniques appreciated.thanks in advance.

import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.sql.*;  public class ex_test extends jframe implements actionlistener {     public static void main(string[] args)      {         ex_test ob=new ex_test();     }     jtextfield tf1;     jbutton b1;     int num1;     public ex_test()     {     super("test");     setlayout(new flowlayout());      tf1=new jtextfield(20);     add(tf1);      b1=new jbutton("ok");     add(b1);      setsize(500,500);     setvisible(true);      b1.addactionlistener(this);      }     public void actionperformed(actionevent ae)     {         if (ae.getactioncommand()=="ok")         {                try             {                    string str=tf1.gettext();                 connection con;                 preparedstatement ps;                 class.forname("sun.jdbc.odbc.jdbcodbcdriver");                 con=drivermanager.getconnection("jdbc:odbc:test");                 ps=con.preparestatement("insert test values('"+str+"')");                 ps.executeupdate();                 con.close();                 ps.close();                 joptionpane.showmessagedialog(null,"data submitted successfully.");             }             catch (exception e)             {                 joptionpane.showmessagedialog(null,"exception occurred.");             }          }     } } 

try - used regex validates input user, more regex find here : http://www.vogella.com/tutorials/javaregularexpressions/article.html

try         {                string str=tf1.gettext();             if ( !(str.matches("[a-za-z]+"))) {                   joptionpane.showmessagedialog(null,"please insert characters.");                   tf1.settext("");             }else{              connection con;             preparedstatement ps;             class.forname("sun.jdbc.odbc.jdbcodbcdriver");             con=drivermanager.getconnection("jdbc:odbc:test");             ps=con.preparestatement("insert test values('"+str+"')");             ps.executeupdate();             con.close();             ps.close();             joptionpane.showmessagedialog(null,"data submitted successfully.");}         }         catch (exception e)         {             joptionpane.showmessagedialog(null,"exception occurred.");         } 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -