1

I am having JavaScript as follows

function DomainValidation() {
        var val = document.getElementById('<%=txtDomainName.ClientID %>').value;
        if (/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/.test(val)) {
            return true;
        }
        else {
            alert("Enter Valid Domain Name");
            return false;
        }
    }

for checking the valid domain name. It is working fine except when I try to enter the domain name with only two character it is not accepting. Since I have no idea of using Regular Expression, so wanna know where I should make change so that it accept domain name with only two characters also.

Note:- Before marking this a duplicate and showing me this I would like to inform that the above script is working fine but I want it to accept the domain name with only two characters too.

Community
  • 1
  • 1
Naved Ansari
  • 650
  • 2
  • 13
  • 31
  • 1
    Can you provide an example of a two-character domain name that you consider valid? – 200_success Dec 28 '15 at 05:38
  • Did you try entering the title of your question into a search engine? I did, and the first four hits came from this very site. – miken32 Dec 28 '15 at 05:39
  • Possible duplicate of [Domain name validation with RegEx](http://stackoverflow.com/questions/10306690/domain-name-validation-with-regex) – miken32 Dec 28 '15 at 05:39
  • may be u guys dint read question carefully. I clearly mentioned that its working fine except for domain name with 2 character – Naved Ansari Dec 28 '15 at 05:41
  • @miken32 may be you should try adding domain name `xy.com` using the script that is mentioned in your provided link – Naved Ansari Dec 28 '15 at 05:43

2 Answers2

5

Just change {1,61} to {0,61}, so that it won't except the middle character.

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

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

Domain names can be tricky,

To support domain names like t.co you can use the below RegExp

^(?!-)[A-Za-z0-9-]+([-.]{1}[a-z0-9]+)*.[A-Za-z]{2,6}$

So you can pass the sample domain as first argument to the function below and it is expected to return true if the input is a valid domain and false otherwise.

const isValidDomainName = (supposedDomainName) => {
  return /^(?!-)[A-Za-z0-9-]+([\-\.]{1}[a-z0-9]+)*\.[A-Za-z]{2,6}$/i.test(
    supposedDomainName
  );
};