簡體   English   中英

如果值包含3個用逗號分隔的字符串,如何從EditText檢查值?

[英]How to check the value from EditText if the value contains 3 string separated with comma?

我在Android Studio上創建了一個程序,其中有一個EditText,用戶可以在其中輸入3個數字,並用逗號分隔,每個數字必須在10到15位之間,代表一個電話號碼。 這是驗證EditText是否具有最少10個和最多15個數字的方法,該方法可以正常工作:

private boolean validateNumberField(EditText editText){

    if(editText.getText().toString().length()<10 || editText.getText().toString().length()>15){
        editText.setError(" The number field should have minimum 10 digits and a maximum of 15");
        return false;
    }else {
        return true;
    }
}

問題是:有沒有辦法驗證每個數字是否包含最小10位和最大15位? 謝謝。

當然,使用RegEx最好做到這一點。

但是在您的情況下,拆分字符串可能會成功,因為這沒什么太復雜的:

String string = editText.getText().toString();
String[] parts = string.split(",");
//now just check for each part if the condition is met
foreach ( String part : parts){
    if (part.length()<10 || part.length()>15){  
        editText.setError("whatever");
        return;
    }
}
//if you get to this part, there's no error, everything went fine
//so do whatever you need if there's no error
//or simply return true

嘗試這個:

  String[]arr= editText.getText().toString().split(",");

  boolean valid=false;
  for (String a  : arr) {
     if(validate(a))
     {
     valid=true;
     }
      else
     {
     valid=false;
     break;
     }
  }
if (valid)
{
// valid number
}
else
{
//not valid number
}

並使用下面的函數:

  private boolean validate(String txt){

    if(txt.length()<10 || txt.length()>15){
        return false;
    }
    return true;
}
private boolean validateNumberField(EditText editText){

    String entry = editText.getText().toString();

    String [] phoneNumbers = entry.split(","); // Seperate string on commas

    for(String phone : phoneNumbers){
        if( !hasCorrectDigitNumber(phone) ) {
            // Toast maybe?
            editText.setError(" The number field should have minimum 10 digits and a maximum of 15");
            return false;
        } 
    }

    return true;
}

private boolean hasCorrectDigitNumber(String phone){
    int count = 0;

    for(int i = 0; i < phone.length(); i++){
        char c = phone.charAt(i); 
        if(c <= '9' && c >= '0')
            count++;
    }

    return count >= 10 && count <= 15;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM