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.

5
  • 1
    Can you provide an example of a two-character domain name that you consider valid? Commented Dec 28, 2015 at 5: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. Commented Dec 28, 2015 at 5:39
  • Possible duplicate of Domain name validation with RegEx Commented Dec 28, 2015 at 5:39
  • may be u guys dint read question carefully. I clearly mentioned that its working fine except for domain name with 2 character Commented Dec 28, 2015 at 5:41
  • @miken32 may be you should try adding domain name xy.com using the script that is mentioned in your provided link Commented Dec 28, 2015 at 5:43

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

failed with google.com
yes, https://regex101.com/r/sU2qC4/3, failed with https: //google .com
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
  );
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.