如何在javaswing中验证输入的Textfield是否为手机号码

如何在javaswing中验证输入的Textfield是否为手机号码,java,swing,Java,Swing,如何验证在java swing中输入的Textfield是否是移动电话号码我假设,在按下或按钮时,或通过DocumentListener在修改文本字段内容的同时连续执行验证,基于正则表达式进行验证将解决您的问题。 String number = textfield.getText(); number = number.replace(" ", ""); // Remove spaces, sometimes people seperate different

如何验证在java swing中输入的Textfield是否是移动电话号码我假设,在按下或按钮时,或通过DocumentListener在修改文本字段内容的同时连续执行验证,基于正则表达式进行验证将解决您的问题。

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

图案力以3位数字开头,后跟“-”和7位数字结尾。所有电话号码必须采用“xxx-xxxxxxx”格式。比如说

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=仅允许数字

{3} =长度


{7} =长度

无需使用正则表达式。相反,请使用适当的组件。就是一个,

例子


如果您需要特定于语言环境的格式,那么请更改MaskFormatter实例。

以实现最安全的解决方案

导入java.awt.Dimension;
导入java.text.ParseException;
导入javax.swing.*;
导入javax.swing.text.*;
公共类格式化电话{
私有静态void createAndShowUI(){
JPanel面板=新的JPanel();
JFormattedTextField telefoonnummer=新的JFormattedTextField(createFormatter(“#####/#####”);
维度teleSize=telefoonnummer.getPreferredSize();
telefoonnummer.setPreferredSize(新尺寸(100,teleSize.height));
JFormattedTextField电话号码a=新的JFormattedTextField(新的JFormattedTextField.AbstractFormatter(){
专用静态最终整数最大长度=9;
私有MaskFormatter smallFormat=createFormatter(“##/######”);
private MaskFormatter bigFormat=createFormatter(“####/######”);
私有静态最终长serialVersionUID=1L;
@凌驾
公共对象stringToValue(字符串文本)引发ParseException{
字符串simpleText=text.replaceAll(“/”,“”)。replaceAll(“\\.”,“”);
if(simpleText.length()=MAX_length){/>=9
valueText=valueText.substring(0,9);
返回valueText.substring(0,3)+“/”+valueText.substring(3);
}否则{
返回null;
}
}
@凌驾
受保护的DocumentFilter getDocumentFilter(){
返回新的DocumentFilter(){
@凌驾
public void insertString(FilterBypass fb、int偏移量、字符串文本、,
AttributeSet attr)引发BadLocationException{
如果(!text.matches(\\d+)){
返回;
}
字符串fbText=fb.getDocument().getText(0,fb.getDocument().getLength()).replaceAll(“/”,”);
如果(fbText.length()+text.length()>最大长度){
返回;
}
super.insertString(fb、偏移量、文本、属性);
}
@凌驾
公共无效替换(FilterBypass fb,整数偏移,整数长度,
字符串文本,属性集属性)引发BadLocationException{
如果(!text.matches(\\d+)){
返回;
}
字符串fbText=fb.getDocument().getText(0,fb.getDocument().getLength()).replaceAll(“/”,”);
如果(fbText.length()+text.length()-长度>最大长度){
返回;
}
super.replace(fb、偏移量、长度、文本、属性);
}
};
}
});
电话号码b.setPreferredSize(telefoonnumer.getPreferredSize());
添加面板(telefoonnummer);
面板。添加(电话号码a);
面板。添加(电话号码b);
JFrame=新JFrame(“格式电话号码”);
frame.getContentPane().add(面板);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}
静态MaskFormatter createFormatter(字符串格式){
MaskFormatter格式化程序=null;
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);
        }

    }

}
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() {
    }
}