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!
2
Answers
I have added some more conditions to your validator function :
I would first sanitize the URL with something like:
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 usingUri.tryParse
instead.An empty host does not necessarily imply an invalid URL. For example, all of the following would have an empty host:
file:///some/path
mailto:[email protected]
tel:+1-800-555-1212
(But maybe that’s okay if you don’t care about such URLs.)