faqts : Computers : Programming : Languages : JavaScript : Language Core : Regular Expressions

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

30 of 70 people (43%) answered Yes
Recently 0 of 10 people (0%) answered Yes


How do I validate Url's w/reg exp [accepting ONLY http's]

Dec 23rd, 2000 04:48
Juergen Thelen, Frank Cyphers,

Here's what I sometimes use for this kind of stuff:
var myRegExp=/(http:\/\/)/gi;
var myArray = myRegExp.exec(document.myForm.myTextfield.value);
if ((myArray) && (myArray.length == 1) && (myRegExp.lastIndex == 7))
  // textfield content is most probably a valid "http://" URL
This code only ensures that the textfield contains the text "http://" 
exactly once (disregarding upper/lowercase), and that there are no 
leading characters in front of it at all.
Of course this is no waterproof validation, because no further checking 
is done to make sure that the textfield content completely complies to 
the syntax rules of an URL using the "http:" scheme, but if all of the 
previously checked conditions have been met, it is at least most likely 
a valid HTTP URL...
I never felt a need to make this waterproof (and was always too lazy to 
do it, to be honest), but if you're willing to spend the time that this 
operation will take, just grab RFC1738, RFC1034, RFC1123, RFC1808 and 
RFC2396 somewhere, and go dig your tunnel... :O)
If you don't know of or where to get RFCs, just hop here:
Hope this helps.