ruru
ruru

Reputation: 47

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

I create a program on Android Studio, where i have an EditText in which the user can enter 3 numbers separated with comma, and each number must be between 10 and 15 digits, representing a phone number. Here is the method that verify if the EditText has min 10 and max 15 numbers which works fine:

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

The qestion is: Is there a way to verify if each numbers contains min 10 and max 15 digits? Thank you.

Upvotes: 0

Views: 578

Answers (3)

Sunshinator
Sunshinator

Reputation: 950

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

Upvotes: 0

pouyan
pouyan

Reputation: 3449

try this:

  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
}

and use function bellow:

  private boolean validate(String txt){

    if(txt.length()<10 || txt.length()>15){
        return false;
    }
    return true;
}

Upvotes: 1

Vucko
Vucko

Reputation: 7479

Surely this can be best done with RegEx.

But in your case, splitting the string might do the trick because this is nothing too complicated:

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

Upvotes: 2

Related Questions