How to validate if Textfield entered is a mobile number in java swing
Asked
Active
Viewed 1.7k times
2
-
can you define `mobile number` , it is country dependent. – jmj Nov 02 '11 at 11:50
-
that won't fix it for all case – jmj Nov 02 '11 at 11:54
-
Give a example mobile no, otherwise, this question will be closed. – Abimaran Kugathasan Nov 02 '11 at 11:57
-
http://stackoverflow.com/questions/1102891/how-to-check-a-string-is-a-numeric-type-in-java – jmj Nov 02 '11 at 11:59
5 Answers
4
No need to resort to regular expressions. Instead, use the appropriate component. That is, a JFormattedTextField
.
Example
import java.awt.FlowLayout;
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.text.MaskFormatter;
public final class FormattedTextFieldDemo {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
try {
createAndShowGUI();
}
catch (ParseException e) {
e.printStackTrace();
}
}
});
}
private static void createAndShowGUI() throws ParseException{
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(new JPhoneNumberFormattedTextField());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static final class JPhoneNumberFormattedTextField extends JFormattedTextField{
private static final long serialVersionUID = 8997075146338662662L;
public JPhoneNumberFormattedTextField() throws ParseException{
super(new MaskFormatter("(###) ###-####"));
setColumns(8);
}
}
}
And if you need the format to be locale-specific, then change the MaskFormatter
instance.

mre
- 43,520
- 33
- 120
- 170
-
-
hehehe if I'd be your Customer, how can you add telephone number to my CellPhone (in international form == +00 000 000 000 0000) to this mask, agreed yes that good question, sure I never neeed to solved that and don't know correct way, only to implements some international phone format directly – mKorbel Nov 02 '11 at 12:44
-
on todays world doesn't exists some Locale, everything are everywhere, maybe Locale is required in education and public administration :-) – mKorbel Nov 02 '11 at 12:53
2
for safiest workaround you have to implement DocumentListener
import java.awt.Dimension;
import java.text.ParseException;
import javax.swing.*;
import javax.swing.text.*;
public class FormatPhone {
private static void createAndShowUI() {
JPanel panel = new JPanel();
JFormattedTextField telefoonnummer = new JFormattedTextField(createFormatter("###/######"));
Dimension teleSize = telefoonnummer.getPreferredSize();
telefoonnummer.setPreferredSize(new Dimension(100, teleSize.height));
JFormattedTextField telephoneNumberA = new JFormattedTextField(new JFormattedTextField.AbstractFormatter() {
private static final int MAX_LENGTH = 9;
private MaskFormatter smallFormat = createFormatter("##/######");
private MaskFormatter bigFormat = createFormatter("###/######");
private static final long serialVersionUID = 1L;
@Override
public Object stringToValue(String text) throws ParseException {
String simpleText = text.replaceAll("/", "").replaceAll("\\.", "");
if (simpleText.length() < MAX_LENGTH) {
return smallFormat.stringToValue(text);
} else {
return bigFormat.stringToValue(text);
}
}
@Override
public String valueToString(Object value) throws ParseException {
if (value != null) {
String valueText = (String) value;
System.out.println(valueText.length());
}
return smallFormat.valueToString(value);
}
});
telephoneNumberA.setPreferredSize(telefoonnummer.getPreferredSize());
JFormattedTextField telephoneNumberB = new JFormattedTextField(new JFormattedTextField.AbstractFormatter() {
private static final int MAX_LENGTH = 9;
private static final long serialVersionUID = 1L;
@Override
public Object stringToValue(String text) throws ParseException {
return text.replaceAll("/", "");
}
@Override
public String valueToString(Object value) throws ParseException {
if (value == null) {
return null;
}
String valueText = (String) value;
if (!valueText.matches("\\d+")) {
return null;
}
if (valueText.length() < MAX_LENGTH - 1) { // < 8
return null;
}
if (valueText.length() == MAX_LENGTH - 1) { // == 8
return valueText.substring(0, 2) + "/" + valueText.substring(2);
} else if (valueText.length() >= MAX_LENGTH) { // >= 9
valueText = valueText.substring(0, 9);
return valueText.substring(0, 3) + "/" + valueText.substring(3);
} else {
return null;
}
}
@Override
protected DocumentFilter getDocumentFilter() {
return new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset, String text,
AttributeSet attr) throws BadLocationException {
if (!text.matches("\\d+")) {
return;
}
String fbText = fb.getDocument().getText(0, fb.getDocument().getLength()).replaceAll("/", "");
if (fbText.length() + text.length() > MAX_LENGTH) {
return;
}
super.insertString(fb, offset, text, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
if (!text.matches("\\d+")) {
return;
}
String fbText = fb.getDocument().getText(0, fb.getDocument().getLength()).replaceAll("/", "");
if (fbText.length() + text.length() - length > MAX_LENGTH) {
return;
}
super.replace(fb, offset, length, text, attrs);
}
};
}
});
telephoneNumberB.setPreferredSize(telefoonnummer.getPreferredSize());
panel.add(telefoonnummer);
panel.add(telephoneNumberA);
panel.add(telephoneNumberB);
JFrame frame = new JFrame("Format Phone Number");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
static MaskFormatter createFormatter(String format) {
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter(format);
formatter.setPlaceholderCharacter('.');
} catch (java.text.ParseException exc) {
System.err.println("formatter is bad: " + exc.getMessage());
System.exit(-1);
}
return formatter;
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowUI();
}
});
}
private FormatPhone() {
}
}

mKorbel
- 109,525
- 20
- 134
- 319
1
The pattern force starting with 3 digits followed by a “-” and 7 digits at the end. All phone numbers must be in “xxx-xxxxxxx” format. For example
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidatePhoneNumber {
public static void main(String[] argv) {
String sPhoneNumber = "605-8889999";
//String sPhoneNumber = "605-88899991";
//String sPhoneNumber = "605-888999A";
Pattern pattern = Pattern.compile("\\d{3}-\\d{7}");
Matcher matcher = pattern.matcher(sPhoneNumber);
if (matcher.matches()) {
System.out.println("Phone Number Valid");
} else {
System.out.println("Phone Number must be in the form XXX-XXXXXXX");
}
}
}
\\d = only digit allow
{3} = length
{7} = length

WarFox
- 4,933
- 3
- 28
- 32

Abimaran Kugathasan
- 31,165
- 11
- 75
- 105
0
I would assume that doing validation based on Regular Expressions, when pressing or button, or through a DocumentListener to have the validation performed continuously while modifying the contents of the text field, would solve your problem.

Anders
- 660
- 3
- 12
0
What about:
String number = textfield.getText();
number = number.replace(" ", ""); // Remove spaces, sometimes people seperate different
// parts of the number with them
boolean valid = number.matches("[0-9]{6,10}"); // Assuming a number can have any length
// from 6 to ten

Sibbo
- 3,796
- 2
- 23
- 41