How to Validate TextField in Java Swing

We can define a validation to validate user input for textfields, password fields etc.If the user entered value does not match the validation pattern, a message appears.

 

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

import java.util.regex.*;

class validation extends JFrame

{

JTextField text;

JLabel lid,lmess;

JPanel pa;

validation()

{

text=new JTextField(15);

lid=new JLabel("ID:");

lmess=new JLabel("Pls!Enter only Numeric Value in the textfield");

pa=new JPanel();

pa.add(lid);

pa.add(text);

pa.add(lmess);

lmess.setVisible(false);

text.addKeyListener(new KeyAdapter()

{

public void keyTyped(KeyEvent e)

{

String input=text.getText();

Pattern patt = Pattern.compile("[a-z,A-Z,%@!()*~^!#$%&+/-]");//restrictions all symbols

Matcher m = patt.matcher(input);

if (m.find())

{

lmess.setVisible(true);

lmess.setForeground(Color.BLUE);

}

else

{

lmess.setVisible(false);

}

}

});

add(pa);

setVisible(true);

setSize(300,100);

}

public static void main(String[]args)

{

validation valid=new validation();

}

}

textfield validation in Java Swing

Explanation...

A good programmer will take steps to prevent the user from entering invalid data( like symbols@ # % ^ & etc).The message has to be execute each time the user enters incorrect characters or invalid values in the textfield.