简体   繁体   English

Javascript验证域点com

[英]Javascript Validate domain dot com

im trying to make a javascript input validator. 我试图做一个JavaScript输入验证器。

I want to check the input if its in the correct domain format. 我想检查输入的域格式是否正确。 It must check the specific input when the submit button is pressed. 当按下提交按钮时,它必须检查特定的输入。

If it is not the correct format, the form will not submit. 如果格式不正确,则不会提交表格。 I am not sure with my RegExp format. 我不确定我的RegExp格式。 Also not sure with the whole code if it will run depending on how i wanted it to be. 也不确定整个代码是否会根据我想要的方式运行。

Here's my code : 这是我的代码:

var x1=document.forms["leform"]["domain"].value;
 validomain(x1);
function validomain(les) {
    var tdomain = new RegExp('/[:alpha:]+/./[:alpha:]+/');
    if(!tdomain.test(les)){
        alert('not a valid domain format');
        return false;
    }
}

Try 尝试

var tdomain = /^[\w-]+\.\w+$/;

\\w are word characters. \\ w是单词字符。

The . 的。 is special (matches any character) and must be escaped. 是特殊字符(与任何字符匹配),必须转义。

Also, you might want to research what a valid domain can look like. 另外,您可能想研究有效域的外观。 (Want to match subdomains? what about domains with international characters?) (要匹配子域名吗?具有国际字符的域名怎么办?)

based on your comment: 根据您的评论:

examp.le any small letter(probably max 20 chars) dot any small latter again (max 4 chars) 例如,任何小写字母(最多20个字符)都再点一个小字母(最多4个字符)

var x1=document.forms["leform"]["domain"].value;
 validomain(x1);
function validomain(les) {
    if ( !String(les).match(/^[a-z]{1,20}\.[a-z]{1,4}$/) ) {
        alert('not a valid domain format');
        return false;
    }
}

you can try this regex too: 您也可以尝试此正则表达式:

function validomain(les) {
   var pattern = new RegExp(/([a-z0-9-]+\.(?:com))(?:\/|$)/)
   if(!pattern.test("les"))'{
      alert('not a valid domain format');
      return false;
   }
}

@Crayon Violent is right may be you have a problem elsewhere in your code @Crayon Violent是正确的,可能是您在代码中的其他地方遇到了问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM