我在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/