Home > OS >  Uri parse does not parse
Uri parse does not parse

Time:05-09

  String baseUrl = "httpswwwmywebsiteit";
  Uri primaUrl = Uri.parse(baseUrl);
  print(primaUrl); // returns httpswwwmywebsiteit

Is this a valid uri? How can I spot malformed urls? For example where having one slash instead of two? Or mispelled scheme?

CodePudding user response:

Irhn on "Uri.parse doesn't throw FormatException"

The Dart Uri class is not validating registered schemes, only the RFC 3986 grammar.
The only special caseing offered by the Uri class is recognition of the default port for the HTTP and HTTPS protocols.

You should watch this: Dart / Flutter - Validating a string for URL

CodePudding user response:

The string "httpswwwmywebsiteit" is a valid URI Reference (according to RFC 3986.

It's a relative-part with a path-noscheme which is just a single URI path segment.

If you want to validate that something is a valid URI, and has a scheme and path, you need to check for that.

if (!primaUrl.hasScheme || !primarUrl.hasAuthority || primaUrl.path.isEmpty) {
  // Or whicever requirements you have on the URI.
  throw ArgumentError.value(baseUrl, "baseUrl", "Not a full URI");
}

Checking whether the scheme is valid requires you to define what that means, then you can check that primaUrl.scheme satisfies that.

  •  Tags:  
  • dart
  • Related