gpt4 book ai didi

android - 如何在 TextWatcher 中验证 URL 同时匹配空字符串

转载 作者:行者123 更新时间:2023-11-30 00:11:19 24 4
gpt4 key购买 nike

我有一个 TextWatcher 检查 URL 是否有效。如果 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.comhttps://example.com、空字符串。 https://www.example.com 有时会被接受或拒绝。 www.example.comexample.com 被拒绝。

最佳答案

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
}

source

关于android - 如何在 TextWatcher 中验证 URL 同时匹配空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48078508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com