如何验证输入的文本字段是否是java swing中的移动号码

时间:2011-11-02 11:49:16

标签: java swing

如何验证Textfield输入的是否是java swing中的手机号码

5 个答案:

答案 0 :(得分:4)

无需诉诸正则表达式。相反,请使用适当的组件。也就是说,JFormattedTextField

实施例

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);
        }

    }

}

enter image description here

如果您需要将格式设置为特定于语言环境,请更改MaskFormatter实例。

答案 1 :(得分:2)

对于最安全的解决方法,您必须实施DocumentListener

enter image description here

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

答案 2 :(得分:1)

模式强制以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} =长度

答案 3 :(得分:0)

我认为基于正则表达式进行验证,按下或按钮时,或通过DocumentListener进行验证,以便在修改文本字段的内容时连续执行验证,这将解决您的问题。

答案 4 :(得分:0)

怎么样:

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