Click to See Complete Forum and Search --> : [RESOLVED] Javascript URL validator allows spaces?


sneakyimp
02-14-2008, 02:17 PM
I have written this URL validator function in Javascript:

function checkURL(sURL) {
var re = new RegExp("^(http:\/\/|https:\/\/|www\.|//)(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?(\/)*$", 'i');
return sURL.match(re);
}


Although there is not a single spaces in my regular expression, it will return true for a url containing spaces like "http://foo bar.com". It looks to me like I have properly escaped all the periods so they don't match just anything. Can anyone help me figure out what the problem is?

Weedpacket
02-14-2008, 04:05 PM
Try \\\. : I would have thought \\. would have been sufficient, but maybe something is broken somewhere or I'm just too tired to think through all the escaping requirements. Further alternatives:

Use [.] instead.

'/' is only a special character in regular expressions if you're using it to quote the regular expression in the first place; since you're not, you don't need to escape it. Or you can, and write var re = /^(http:\/\/|https:\/\/|www\.|\/\/)(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?(\/)*$/i; and take Javascript's string-escaping requirements out of consideration.

But the hassle you're having can be boiled down a bit if that helps:
function checkDomain(sDomain) {
var re = new RegExp("^([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+$", 'i');
return sDomain.match(re);
}

checkDomain('foo bar.com');

sneakyimp
02-14-2008, 06:03 PM
Thanks for the 'boiling down' bit. It would appear that problem is in fact related to the escaped period. Thanks also for the [.] suggestion which seems to fix it.