1

我有一个检查 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拒绝。

4

1 回答 1

1
String pattern = "(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})";

将匹配以下情况

  • http://www.foufos.gr
  • https://www.foufos.gr
  • http://foufos.gr
  • http://www.foufos.gr/kino
  • http://www.t.co
  • http://t.co
  • http://werer.gr
  • www.foufos.gr
  • www.mp3.com
  • www.t.co

将不匹配以下

  • www.foufos
  • http://www.foufos
  • http://foufos
  • www.mp3#.com
  • www.foufos-.gr
  • www.-foufos.gr

关于空字符串,首先检查它是否为空,然后检查模式

if(yourstring.length() == 0 ||  yourstring.matches(pattern)) {
  // do something
}else{
   // show validation warning
}

来源

于 2018-01-03T13:41:43.920 回答