Valid Domain/Subdomain Method
Custom Valid Domain/Subdomain Validation
by jacobwsmith
JavaScript
console.clear();
// JUST NEED THE DOMAIN OR SUBDOMAIN NAME
// No port ':'
// No http:// or https://
// Invalid Characters
// subdomain can be ok
// www is ok
// 'a.a' is a valid domain
function isUrl(str) {
// str exists
if (typeof str !== 'string' || str.length < 3 ) {
return false;
}
// Only contains letters numbers and '.', '-'
if (/^[a-zA-Z0-9.-]*$/.test(str) === false) {
return false
}
// Contains one '.'
if(!str.includes('.')){
return false;
}
// can't start or end with '.' or '-'
if(str[0] === '.' || str[0] === '-' || str[str.length - 1] === '.' || str[str.length - 1] === '-') {
return false;
}
// can't have these either
if(str.includes('.-') || str.includes('-.')){
return false;
}
// testing against regEx
/*
const ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
const ValidHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$";
if(!/ValidHostnameRegex/.test(str) && !/ValidIpAddressRegex/.test(str)){
return false;
}
*/
return true;
}
assert('', false);
assert(123, false);
assert(null, false);
assert('a.a', true);
assert(undefined, false);
assert('www.vizu.com', true);
assert('123.com', true);
assert('123', false);
assert('http://www.vizu.com', false);
assert('.vizu.com', false);
assert('vizu.com.', false);
assert('vizu-foo.com', true);
assert('-vizufoo.com', false);
assert('vizufoo.com-', false);
function assert(val, expected) {
const actual = isUrl(val);
if (actual === expected) {
console.log('PASSED')
} else {
console.log(`FAILED: for ${val} expected \"${expected}\" but got \"${actual}\"`)
}
}