java - 如果值包含 3 个以逗号分隔的字符串,如何检查 EditText 中的值?

标签 java android xml

我在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 位数字? 谢谢。

最佳答案

当然,这最好用正则表达式来完成。

但在你的情况下,分割字符串可能会成功,因为这并不是太复杂:

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

关于java - 如果值包含 3 个以逗号分隔的字符串,如何检查 EditText 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37794224/

相关文章:

Java 使用类作为集合来添加项目

android - 如何根据手机加速度计算距离

xml - 如何使用 saxon 内置目录功能

c# - XmlSerializer 用问号替换非 ASCII 字符 '?'

java - Bean 到 XML 注释 : how to process nested structure

Java 递归和归并排序

java - 使用 junit 测试 map 时使用通用有界通配符

java - 即使条件变为 false,代码也会在 if block 内运行

android - RxBinding TextChanges 不会继续发出文本更改

c# - 使用 System.ServiceModel 在 Xamarin 中使用 WCF REST 基本身份验证服务