Validate if a string is a URL

Godot Version

4.2

Question

What is the best way to check if a string is a proper URL before handing it over to an HTTPRequest?

I see that String has is_valid_ip_address() but could not find anything like is_valid_url()

Thanks!

Max

1 Like

I would use the RegEx object.

And run a regular expression on the string:

1 Like

I would check it via HTTPRequest,
uses a C++ function which is not available via Gdscript.


func _ready():
	var url = "https2://godotengine.org"

	var http_request = HTTPRequest.new()
	add_child(http_request)
	var error = http_request.request(url)

	match error:
		ERR_INVALID_PARAMETER:
			print("ERR_INVALID_PARAMETER: if given string is not a valid URL format")
		_:
			print("error:", error)

method-request

But this error output in the editor cannot be suppressed. It wouldn’t bother me.

image

I could have thought of that on myself :person_facepalming:
Thanks @BirchDev

For reference:

var urlRegex = RegEx.new()
urlRegex.compile('^(ftp|http|https)://[^ "]+$')
var result = urlRegex.search(post.account.avatar_static)
	
if result:
   ...

Thanks for the recommendation but actually the ERROR is what bothered me in the first place :smiley:

1 Like

HTTPRequest::_parse_url

looks to me as if Godot only lets through “https” and “http”, so ftp should also produce the error output :slight_smile: