Online Shopping : Computers : Programming : Languages : JavaScript

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

50 of 74 people (68%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

How do I validate the format of a URL or email
How do I validate the format of a URL or email
How do I validate the format of a URL or email

Apr 7th, 2008 23:08
ha mo, Mark Szlazak, "Mastering Regular Expressions" by Jeffrey Friedl


The following uses regular expressions adapted from Jeffrey Friedl's 
book to check the format of a URL or email string. 
In the URL regular expression the protocol part (i.e, ftp, http or 
https) is optional so the URL can start with the hostname. The regular 
expression also accepts an optional port number and has a heuristic 
that works well for an optional trailing part that begins with a 
forward slash (/). 
<HTML>
<HEAD>
<SCRIPT>
function isURL (url) {
  var urlPattern = /^(?:(?:ftp|https?):\/\/)?(?:[a-z0-9](?:[-a-z0-9]*[a-
z0-9])?\.)+
(?:com|edu|biz|org|gov|int|info|mil|net|name|museum|coop|aero|[a-z][a-
z])\b(?:\d+)?(?:\/[^;"'<>()\[\]{}\s\x7f-\xff]*
(?:[.,?]+[^;"'<>()\[\]{}\s\x7f-\xff]+)*)?/;
  return urlPattern.test(url.toLowerCase());
}
function checkURL (field) {
  if (!isURL(field.value)) {
    alert('Please enter correct url!');
    field.focus();
    field.select();
  }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="aForm">
	<INPUT TYPE="text" NAME="url">
	<INPUT TYPE="button" NAME="check" VALUE="Check URL" 
ONCLICK="checkURL(this.form.url);">
</FORM>
</BODY>
</HTML>
A similar arrangement for email format validation uses the following 
regular expression.
    var emailPattern = /^\w[-.\w]*\@[-a-b0-9]+(?:\.[-a-b0-9]+)*\.
(?:com|edu|biz|org|gov|int|info|mil|net|name|museum|coop|aero|[a-z][a-
z])\b/;
http://www.businessian.com
http://www.computerstan.com
http://www.financestan.com
http://www.healthstan.com
http://www.internetstan.com
http://www.moneyenews.com
http://www.technologystan.com
http://www.zobab.com
http://www.healthinhealth.com