Validate site/domain via javascript
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 vi开发者_开发技巧a 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
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.
精彩评论