JavaScript regular expression validation for domain name?

后端 未结 6 1239
野的像风
野的像风 2020-12-17 23:45

How to check a valid domain name and username with regular expression in JavaScript?

function validate()
{
    var         


        
6条回答
  •  悲哀的现实
    2020-12-18 00:22

    This maybe slightly off-topic but after searching the internet for several hours and trying out various RegExp's (non of which would work for me). I decided to write my own function that would take a list of valid TLD extensions and run a validation against them. So for anyone who is having a similar problem, please check out my Javascript function:

    function domainCheck(dom) {
        // convert input to lowercase.
        dom = dom.toLowerCase();
        // find the first occurance of '.'
        pos = dom.indexOf(".");
        // Using the first occurance of '.'
        // find the extension submitted.
        tld = dom.substring(pos);
        switch(tld) {
            // TLD's to accept.
            case '.com': return true; break;
            case '.co.uk': return true; break;
            case '.eu': return true; break;
            case '.io': return true; break;
            case '.co': return true; break;
            case '.net': return true; break;
            default: return false;
        }
    }
    

    I have created a demo using this function here: http://jsfiddle.net/netfox/MhPG8/19/embedded/result/

提交回复
热议问题