Hosting Solutions  
 
   |  Tutorials Home  |  Privacy | 









Secured by RapidSSL



Validating URL's

Validating URLs and File Names

link = /^(ftp|http):\/\/\S+\/\S+\.(gif|jpg)$/i

To validate an absolute url, in this case one that points to an image file, we first want to check the url that is entered, so the regexp (regular expression) should begin with /^ and ends with $/. The first part can be either "ftp" or "http", separated by the vertical bar | symbol (which you may recall means 'OR' in javascript).

link = /^(ftp|http)

The next odd-looking set of characters are simply the usual '://' that follows; since the forward slashes are also special regexp characters, they have to be escaped, using the backslash for this purpose, for each of the forward slashes... this denotes that we do not want to use them here as special characters, but only as regular forward slashes.

link = /^(ftp|http):\/\/

Next, given the variety of domain names, we don't want to be too restrictive, so we can just use \S+ to denote what follows can be one or more characters, with underscores or dashes but no spaces.

link = /^(ftp|http):\/\/\S+

After that, we need to put in a forward slash to separate the domain name from the file name, but remember, we have to escape it. After that we insert another \S+ for the file name.

link = /^(ftp|http):\/\/\S+\/\S+

The file name needs to have a dot between it and its extension, and it must be escaped: \. Next comes the extensions, and here we'll just test for "gif" or "html", using the vertical bar to signify "OR".

link = /^(ftp|http):\/\/\S+\/\S+\.(gif|html)

And finally, we insert the string symbol $ to denote the end of the string, and use the forward slash to close the expression. In order to allow either upper or lower case to be entered by the user, we add the special character "i" at the very end.

link = /^(ftp|http):\/\/\S+\/\S+\.(gif|jpg)$/i

There you have it. Now, the user must at least enter the url in a valid format. You can use the function listed below, which will refocus and select the user's entry if it is invalid.

<script language="javascript" type="text/javascript">
<!--
link = /^(file|http):\/\/\S+\/\S+\.(gif|jpg)$/i

function checkit(myForm) {
if (link.test(myForm.imgURL.value)) {
document.chgImg.src = myForm.imgURL.value
}
else {
alert("Invalid URL")
myForm.imgURL.focus()
myForm.imgURL.select()
}
return false
}
//-->
</script>

Your form submission hidden field can call the function like this:

<FORM onSubmit= "return checkit(this)" ACTION= "whatever action.php">



[Printer Friendly Page]






Updated on Thursday, 01~26~2012

Copyright © 1998 - 2012
Bill Payne & Sitebilder© Network