I had found a simple and created an util class that can help in easy way to handle a lot of validations in JText files.
Only in 3 steps in easy way :
1st Step :
- addKeyListener to the text filed.
2nd Step
- implement KeyAdapter to the KeyListener and override Key typed method
3rd Step:
call valid validation that you want from my Util Class TextFiledValidationUtil
the Code Example below :
- workField.addKeyListener(new java.awt.event.KeyAdapter() {
- public void keyTyped(java.awt.event.KeyEvent evt) {
- workFieldKeyTyped(evt);
- }
- });
- workFieldKeyTyped(evt)
- {
- // validate that the impute is string length only 40 .
- DateFiledUtil.assureInputAsString40(evt, this);
- }
and add the TextFiledValidationUtil Class to your work space
public class TextFiledValidationUtil {
- public static void assureInputIsIntegrOnly(KeyEvent evt, AbstractFram frame) {
- char c = evt.getKeyChar();
- JTextField field = getField(evt);
- if (!((c >= '0') && (c <= '9'))) {
- frame.getToolkit().beep();
- evt.consume();
- }
- if (field.getText().length() >= 5) {
- frame.getToolkit().beep();
- evt.consume();
- }
- }
- public static void assureInputIsIntegrOnly(KeyEvent evt, AbstractJDialog frame) {
- char c = evt.getKeyChar();
- JTextField field = getField(evt);
- if (!((c >= '0') && (c <= '9'))) {
- frame.getToolkit().beep();
- evt.consume();
- }
- if (field.getText().length() >= 5) {
- frame.getToolkit().beep();
- evt.consume();
- }
- }
- public static void assureInputAsMobile(KeyEvent evt, PatientForm aThis) {
- char c = evt.getKeyChar();
- JTextField field = getField(evt);
- if (!((c >= '0') && (c <= '9'))) {
- aThis.getToolkit().beep();
- evt.consume();
- }
- if (field.getText().length() >= 11) {
- aThis.getToolkit().beep();
- evt.consume();
- }
- if ((field.getText().length() >= 1 && !field.getText().startsWith("0")) || (field.getText().length() >= 2 && !field.getText().startsWith("01"))) {
- aThis.getToolkit().beep();
- evt.consume();
- }
- }
- private static JTextField getField(KeyEvent evt) {
- return (JTextField) evt.getSource();
- }
- public static void assureInputAsHomePhone(KeyEvent e, PatientForm aThis) {
- char c = e.getKeyChar();
- JTextField field = getField(e);
- if (!((c >= '0') && (c <= '9'))) {
- aThis.getToolkit().beep();
- e.consume();
- }
- if (field.getText().length() >= 11) {
- aThis.getToolkit().beep();
- e.consume();
- }
- }
- public static void assureInputAsString40(KeyEvent e, PatientForm aThis) {
- JTextField field = getField(e);
- if (field.getText().length() >= 40) {
- aThis.getToolkit().beep();
- e.consume();
- }
- }
- }
Click Here to download the TextFiledValidationUtil
No comments:
Post a Comment