Home > other >  What is the best way to implement URL validation in flutter where the user should be able to enter o
What is the best way to implement URL validation in flutter where the user should be able to enter o

Time:06-08

I want to implement URL validation in flutter where the user should be able to enter only one URL in a filed instead of multiple URL's separated by commas, empty spaces.. What is best way to implement this. Thanks.

CodePudding user response:

The scenario here is very simple: there are more than N audio urls stored in the background business database, and the front end gets the URL of the corresponding audio through some business logic, and then finds that a small part of the URL is invalid when playing. So we need to filter out this part of the invalid URL in the background, and then fill up. Analysis of the There are many methods in HTTP: GET, POST, PUT, Delete, option, and so on. In fact, we only need to determine whether the corresponding URL is valid, that is to say, we only need to query the corresponding file information, not the content of the file. The head method, like the GET method, makes a request to the server for a specified resource. Only the server will not return the text portion of the resource. The advantage is that you can retrieve "information about the resource" (meta information or metadata) without having to transfer the entire content. * @param urlStr 待验证的url * @return */ public static boolean verificationUrl(String urlStr) { try { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(3 * 1000); conn.setRequestMethod("HEAD"); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { return true; } return false; } catch (MalformedURLException e) { e.printStackTrace(); return false; } catch (IOException e) { return false; } }

CodePudding user response:

String replacedString = urlStringHere!
         .replaceFirst("http:", "##")
         .replaceFirst("www", "##")
         .replaceFirst(".com", "##")
         .replaceFirst(".net", "##");
if (replacedString.contains("http") ||
    replacedString.contains("www") ||
    replacedString.contains(".com")) {
       return "You can enter only one url";
      } else {
        return null;
          }
  • Related