我有一个检查 URL 是否有效的 TextWatcher。如果 URL 满足“http”、“https”、“www”等可选的 URL 格式,则 URL 是有效的。如果它是一个空字符串,它也是有效的。如果 URL 无效,EditText 将显示错误消息。这是我目前的实现:
private TextWatcher websiteLinkWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(websiteLayout.getError() != null) websiteLayout.setErrorEnabled(false);
}
@Override
public void afterTextChanged(Editable s) {
String websiteFormat = "^(|https?:\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?){0,140}$";
if(s.toString().trim().length() > 140 || !s.toString().matches(websiteFormat)) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
websiteLayout.setErrorEnabled(true);
websiteLayout.setError("The provided website is not valid.");
}
}, 2000);
saveEnabled.setBackgroundColor(getResources().getColor(R.color.grey200));
saveEnabled.setClickable(false);
// disable
}
else {
saveEnabled.setBackgroundColor(getResources().getColor(R.color.blue500));
saveEnabled.setClickable(true);
// enable
}
return;
}
};
正则表达式非常不一致。它唯一的优点是它适用于空字符串(即不显示错误消息)。目前,http://example.com
, https://example.com
, 一个空字符串被接受。https://www.example.com
有时被接受或拒绝。www.example.com
并被example.com
拒绝。