JOptionPane Validation


 

JOptionPane Validation

JOptionPane allow you to create dialog boxes easily for input and output. It makes it easy to pop up a standard dialog box that prompts users for a value or informs something. It is having several methods which may look complex. Here we are going to validate the textfield of JoptionPane dialog.

JOptionPane allow you to create dialog boxes easily for input and output. It makes it easy to pop up a standard dialog box that prompts users for a value or informs something. It is having several methods which may look complex. Here we are going to validate the textfield of JoptionPane dialog.

JOptionPane Validation

JOptionPane allow you to create dialog boxes easily for input and output. It makes it easy to pop up a standard dialog box that prompts users for a value or informs something. It is having several methods which may look complex. Here we are going to validate the textfield of JoptionPane dialog.

JOptionPane String Validation

We have used regular expression that  must first be compiled into an object of the Pattern class. The resulting pattern create a Matcher object that matches arbitrary character sequences against the regular expression. The compile() method compiles the given regular expression into a pattern, then the matcher() method match the given input against this pattern. Here we have defined numbers[0-9] in the regular expression so if any number is found, it will display an error message "Enter only String".

Here is the code:

import javax.swing.*;
import java.util.regex.*;

public class ValidateJOptionPane {
	public static void main(String[] args) {
	String input = JOptionPane.showInputDialog("Enter String: ");
		Pattern p = Pattern.compile("[0-9]");
		Matcher m = p.matcher(input);
		if (m.find()){
       JOptionPane.showMessageDialog(null, "Please enter only string");
		}
	}
}

Output

On entering the integers, it will display error message:

JOptionPane Integer Validation

Here we have restrict the user to enter string, special characters and allowed only integers to input. For this we have again used regular expression and then the  Pattern and Matcher class match the given input against the pattern ["[A-Z,a-z,&%$#@!()*^]"]. If the user enters the string, the dialog will show an error message.

Here is the code:

import javax.swing.*;
import java.util.regex.*;

public class ValidateJOptionPane {
	public static void main(String[] args) {
	String input = JOptionPane.showInputDialog("Enter number: ");
		Pattern p = Pattern.compile("[A-Z,a-z,&%$#@!()*^]");
		Matcher m = p.matcher(input);
		if (m.find()) {
	     JOptionPane.showMessageDialog(null, "Please enter only numbers");
		}
	}
}

Output

On entering the string, it will display error message:

In this tutorial we have learned to validate JOptionPane input.

Ads