JavaScript Reg-ex for sub-domain name

JavaScript Reg-ex for sub-domain name

This one took me a bit so thought it might be worth writing it down.

If you need to validate a field for a valid subdomain name, ie the “subdomain.inthedomain.com” you have a couple of requirments:

1) Field value starts with an letter or number

2) Field value ends with a letter or number

3) All characters between first and last can be a letter, number, or a non-repeating – or .

so lorenzo.gangi-test would be valid.

lorenzo.-gangi..test1 is invalid

This regex should do the trick

<p id="demo">Click the button to display the matches.</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction()
{
var str = "b.o.b-obo123"; 
var temp = new RegExp(/^([a-zA-Z0-9](\w|[.-](?=\w))+[a-zA-Z0-9])$/)
var n=str.match(temp);
document.getElementById("demo").innerHTML=n;
}
</script>
This entry was posted in Javascript. Bookmark the permalink.