Validating a URL

by | February 5,2009

Table of Contents

Validating User Input as a URL Using System.URI

To make sure user input is a valid URL, you can use the System.URI type. Try to convert the raw string into this type. If it works, the string is a valid URI. You can then further examine the converted result to limit validation to only http/https URLs:
function isURI($address) {
	($address -as [System.URI]).AbsoluteURI -ne $null
}

function isURIWeb($address) {
	$uri = $address -as [System.URI]
	$uri.AbsoluteURI -ne $null -and $uri.Scheme -match '[http|https]'
}


isURI('http://www.powershell.com')
isURI('test')
isURI($null)
isURI('zzz://zumsel.zum')

"-" * 50

isURIWeb('http://www.powershell.com')
isURIWeb('test')
isURIWeb($null)
isURIWeb('zzz://zumsel.zum')