如何验证此字符串在 Javascript 中不包含任何特殊字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16827728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:08:52  来源:igfitidea点击:

How to validate this string not to contain any special characters in Javascript?

javascriptvalidation

提问by pynovice

I have a dynamic string like this which may look like:

我有一个像这样的动态字符串,它可能如下所示:

"69.43.202.97"                 OR               "ngs.pradhi.com"

I want to validate these string contains only numbers, english alphabets and "." . I want to validate this in front end using java script. I thought of using regular expression like this:

我想验证这些字符串只包含数字、英文字母和“。” . 我想使用 java 脚本在前端验证这一点。我想过使用这样的正则表达式:

function validatePath() {
    var path = document.getElementById('server_path').value;
    path.match([a-z][0-9])  //or something like this
}

If the path is invalid despite of displaying the alert box I just want to show the error below the text field as soon as the user fills the server path. How can I do that?

如果尽管显示警告框但路径无效,我只想在用户填写服务器路径后立即在文本字段下方显示错误。我怎样才能做到这一点?

My full javascript function looks like this:

我的完整 javascript 函数如下所示:

function validatePath() {
    var path = document.getElementById('server_path').value;
    if (path.search(":") == -1){
        alert("Invalid server path");
    }
    else{
        var host_name = path.split(":")[0]
        if host_name.match("^[a-zA-Z0-9.]*$")) {}

    }

}

}

回答by dshu610

try path.match("^[a-zA-Z0-9.]*$")

尝试 path.match("^[a-zA-Z0-9.]*$")

EDIT: var regex = new RegExp("^[a-zA-Z0-9.]*$"); if(regex.test(host_name)){}

编辑: var regex = new RegExp("^[a-zA-Z0-9.]*$"); if(regex.test(host_name)){}

回答by go-oleg

you can use /^[a-zA-Z0-9.]*$/.test(path)which will return true or false

您可以使用/^[a-zA-Z0-9.]*$/.test(path)which 将返回 true 或 false

回答by gkalpak

You can do the check (including port presence) with a regex like this:

您可以使用这样的正则表达式进行检查(包括端口存在):

^[a-zA-Z0-9\.]+:[0-9]+$

(Note the +instead of *to account for empty path or port (they are not allowed).)

(注意+而不是*考虑空路径或端口(它们是不允许的)。)

If you are using HTML5, consider the newly introduced "pattern" and "required" attributes, which can posdibly save you some JS code.

如果您使用的是 HTML5,请考虑新引入的“pattern”和“required”属性,它们可能会为您节省一些 JS 代码。

See this short demofor an illustration of both technics.

有关这两种技术的说明,请参阅此简短演示

Some links you might find useful:

您可能会发现一些有用的链接:

回答by Isaac

To be different, replace method:

有所不同,替换方法:

if(path.replace(/^[a-z\d.]*$/i,"")=="")