java 如何验证输入的文本字段是否是javaswing中的手机号码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7979811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:32:30  来源:igfitidea点击:

How to validate if Textfield entered is a mobile number in javaswing

javaswing

提问by user1016195

How to validate if Textfield entered is a mobile number in java swing

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

采纳答案by Abimaran Kugathasan

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

模式力以 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 = only digit allow

\\d = 只允许数字

{3} = length

{3} = 长度

{7} = length

{7} = 长度

回答by mre

No need to resort to regular expressions. Instead, use the appropriate component. That is, a JFormattedTextField.

无需求助于正则表达式。而是使用适当的组件。也就是说,一个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);
        }

    }

}

enter image description here

在此处输入图片说明

And if you need the format to be locale-specific, then change the MaskFormatterinstance.

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

回答by mKorbel

for safiest workaround you have to implement DocumentListener

为了最安全的解决方法,你必须实现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() {
    }
}

回答by Anders

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.

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

回答by Sibbo

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