views:

45

answers:

4

I have a signup form where users kan enter their subdomain of choice when creating an account.

http://_________.ourapp.com

I want them to be able to enter valid characters on the __________ part above only. I'm using a text field for that.

Is there a function or some sort of pattern that exists for such situations? Spaces should be filtered, I guess many or all special characters (except numbers, dash and letters) as well?

A: 

Try if(subdomainName.match(/^[a-z0-9][a-z0-9\-]*[a-z0-9]$/))) {...what to do if valid here...} else {...invalid handling here...} - I reckon that ought to work.

Will A
A: 

Javascript 1.2 and later supports regular expressions. That's practically every browser these days.

Using your example of "numbers dashes and letters" as being acceptable subdomains, you could do something similar to the following, probably run when the "submit" button on the form is clicked (and if the match fails, then cancel the submission).

entry.Match(/^[a-zA-Z0-9\-]+$/)

Without more concrete information I really can't give you a full example, but this should get you where you need to go. Of course, keep in mind that javascript validation is not complete for a robust website. You need to re-check this on the server side to protect against people that have javascript disabled (or, in the worst case, malicious users).

Shirik
+1  A: 

Hi there, you can use Regular Expressions to achieve what you need.

Try something like this:

<input id="username" type="text" onblur="validSubdomain()" />


function validSubdomain() {
    var re = /[^a-zA-Z0-9\-]/;
    var val = document.getElementById("username").value;
    if(re.test(val)) {
        alert("invalid");
    }
}
Marko
A: 

So your question is, "What rules do a valid internet domain name follow?"

The answer to that is:

  • it can only contain:
    • the 26 letter of the English alphabet (case-insensitive)
    • numbers (0-9)
    • hyphen/minus sign (-)
  • it must start and end with a letter or number, not a hyphen;
  • the labels must be between 1 and 63 characters long;
  • the entire hostname cannot exceed 255 characters

A domain name is comprised of multiple labels, each separated by a period. A direct subdomain of ourapp.com would be ben.ourapp.com, where ben, ourapp and com are each labels. But you may also optionally allow users to include periods inside of their subdomain, e.g.:

ben.franklin.ourapp.com
i.have.a.clever.vho.st

In those cases, you could allow the user's child domain to be longer than 63 characters (63 * the number of periods in the child domain, with a max size of 244 (.ourapp.com is 11 characters long).

See this Wikipedia article for more info on valid hostnames.

Edit: If you want to support internationalized domain names, things get a bit more complex, though still manageable.

Lèse majesté