PNG PNG - 4 months ago 16
Javascript Question

How to validate domain name using regex?

This is my code for validating domain name.

function frmValidate()
{
var val=document.frmDomin;
if (/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/.test(val.name.value)){
}
else
{
alert("Enter Valid Domain Name");
val.name.focus();
return false;
}
}


and

<form name="frmDomin" action="" method="post" onsubmit="return frmValidate();">
Domain Name : <input type="text" value="" id="name" name="name" />
</form>


Now I entered
http://devp1.tech.in
and it alert the message. I want to enter sub domain also. How to change this? I should not get alert.

Answer

Try this:

^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$

Demo

Comments