2016-04-22 78 views
0

我想限制手機號碼,用戶只能輸入10個號碼,而且不允許輸入符號和字母。我使用的代碼對輸入字母沒有任何限制。下面的代碼移動號碼限制

mno=new TextField(); 
mno.setBounds(340, 460, 0, 0); 
mno.setSize(90, 25); 
mmess=new JLabel("Enter valid mobile no."); 
mmess.setBounds(450, 460, 0, 0); 
mmess.setSize(300, 30); 
mmess.setVisible(false); 

mno.addKeyListener(new KeyAdapter() { 
    public void keyTyped(KeyEvent e) { 
     String input=mno.getText(); 
     Pattern patt = Pattern.compile("^\\d{10}$"); 
     Matcher m = patt.matcher(input); 

     if (m.find()) { 
      mmess.setVisible(true); 
      mmess.setForeground(Color.RED); 
     } 
     else { 
      mmess.setVisible(false); 
     } 
    } 
}); 
+1

什麼是完全缺乏縮進? – khelwood

回答

1

參考,這裏的國家代碼也在手機號碼考慮,你可以,如果再使用這個表達式"^\\+([0-9\\-]?){9,11}[0-9]$"不需要取出相同。

String regex = "^((\\+|00)(\\d{1,3})[\\s-]?)?(\\d{10})$"; 
String str = "+123-9854875847"; 
Pattern p = Pattern.compile(regex); 
Matcher m = p.matcher(str); 

if (m.matches()) { 
    // actions to be taken 
} 
+0

但是,這也不會限制用戶輸入字母。 – Ritu

1

您還可以使用JFormattedTextField

JFormattedTextField text = new JFormattedTextField(
     new MaskFormatter("###-####-####")); 

這將允許在第一個地方只能輸入有效的號碼,而用戶不必猜測格式。在這裏,"###-####-####"只是一個例子,應該用你希望這些手機號碼的格式來代替。 (see the documentation