views:

32

answers:

2

I have a standard html form where the user can specify a website/domain:

favourite website: [ ]

I expect the user to type things like:

[www.google.com] [www.yahoo.com] [www.example.co.jp]

I want to validate the domain/site via javascript so if a user had typed something wrong:

[www...google.com] [www.-example.com]

I tell them straight away.

Can anybody post this javascript ?

Alternatively can anybody point me to a site where I can look at their javascript ?

Many Thanks

A: 

This post describes how to validate URL

Adeel
But it's incorrect. First I am not validating a URL just a domain.Second according to that script http://www.-10.com is a valid URLBAD
Chez
A: 

Doing a Google search I found this: Validating Domain Names in a blog by Shaun Inman.

His method appears robust and may be exactly what you're looking for. I would be a bit concerned about having to stay on top of any changes to the TLD list.

Another option, as one reader on his blog suggested, is to keep it simple and check for one character, a dot, and at least two characters after the dot. Ex: a.bc. That has the advantage of not requiring maintenance and not frustrating your users.

Another option, if you want to be very robust is to perform a DNS lookup. You won't be able to do that in your JavaScript alone, but with a simple Ajax call you can get it to work server side.

JavaScript: (uses jQuery)

// domain_msg is the id of the div you want your answer placed
var domain_to_lookup = 'www.google.com';
jQuery('#domain_msg').load('http://yourwebsite.com/ajaxurl', {lookup: domain_to_lookup});

Of course you'll need a server side script to check the domain. $_POST['lookup'] will be the value (www.google.com in this example) and you can pass that to gethostbyname() (PHP). I'm sure other languages have a similar mechanism. Just return "Domain OK" or "Enter a valid Domain" or whatever your want your text to be. If you're new to Ajax or jQuery, this post will help you out: Using AJAX to Validate Forms.