1

URL が有効かどうかをチェックする TextWatcher があります。「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.comhttps://example.com、空の文字列が受け入れられます。https://www.example.com時々、受け入れたり拒否したりします。拒否されますwww.example.comexample.com

4

1 に答える 1