Home > OS >  How to format the url?
How to format the url?

Time:01-22

I want to format url. Here is an example:

Input:

www.google.com

or

google.com

Output:

https://www.google.com/

I need to format the url because I'm using a validator function that needs to check if the text is a url. When I type www.google.com or google.com it says it's not a url because it requires https at the beginning of the text.

My code:

validator: (value) {
  if (value == null) {
    return null;
  }
  if (Uri.parse(value).host.isEmpty) {
    return "Please type a valid url";
  }
},

Feel free to leave a comment if you need more information.

How to format the url? I would appreciate any help. Thank you in advance!

CodePudding user response:

I have added some more conditions to your validator function :

validator: (value) => {
  if (value == null) {
    return null;
  }
  if (!value.startsWith("https://")) {
    value = "https://"   value;
  }
  if (!value.startsWith("https://www.") && !value.startsWith("https://")) {
    value = "https://www."   value.substring(8);
  }
  if (Uri.parse(value).host.isEmpty) {
    return "Please type a valid url";
  }
}

CodePudding user response:

I would first sanitize the URL with something like:

String ensureScheme(String url) {
  var uri = Uri.tryParse(url);
  if (uri == null || !uri.hasScheme) {
    url = 'https://$url';
  }
  return url;
}

which would add an https URL scheme only if no scheme is already present, thereby avoiding mangling URLs that use other schemes (e.g. file:///some/path, mailto:[email protected], ssh://[email protected], tel: 1-800-555-1212).

Additionally, note that your Uri.parse(value).host.isEmpty check is not quite correct:

  • Uri.parse will throw an exception if given unparsable input (e.g. ':'). You probably should be using Uri.tryParse instead.

  • An empty host does not necessarily imply an invalid URL. For example, all of the following would have an empty host:

    (But maybe that's okay if you don't care about such URLs.)

  • Related