Skip to content

Instantly share code, notes, and snippets.

@mohammadwali
Last active June 15, 2018 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohammadwali/af11bb30b7a687a8908c9496c49f4faa to your computer and use it in GitHub Desktop.
Save mohammadwali/af11bb30b7a687a8908c9496c49f4faa to your computer and use it in GitHub Desktop.
Validate a subdomain with JavaScript, inspired from https://gist.github.com/stuartbain/7212385
const MIN_LENGTH = 5;
const MAX_LENGTH = 63;
const ALPHA_NUMERIC_REGEX = /^[a-z][a-z\-]*[a-z0-9]*$/;
const START_END_HYPHEN_REGEX = /\A[^-].*[^-]\z/i;
const reservedNames = ['www', 'ftp', 'mail', 'pop', 'smtp', 'admin', 'ssl', 'sftp'];
const validateSubdomain = subdomain => {
//if is reserved...
if (reservedNames.includes(subdomain))
throw new Error('cannot be a reserved name');
//if is too small or too big...
if (subdomain.length < MIN_LENGTH || subdomain.length > MAX_LENGTH)
throw new Error(`must have between ${MIN_LENGTH} and ${MAX_LENGTH} characters`);
//if subdomain is started/ended with hyphen or is not alpha numeric
if (!ALPHA_NUMERIC_REGEX.test(subdomain))
throw new Error(
(subdomain.indexOf('-') === 0 || subdomain.indexOf('-') === (subdomain.length - 1)) ?
'cannot start or end with a hyphen' :
'must be alphanumeric (or hyphen)'
);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment