javascript 如何仅限制特殊字符和 (/,*,+)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28872515/
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-28 09:41:20  来源:igfitidea点击:

how to restrict special characters and ( /,*,+) only

javascriptregexhtmlvalidationtextbox

提问by Pavan Alapati

We have one text Field.We know how to restrict special characters.But We need Allow alphabet and Numbers and hyphen(-) only.No need Sepcial characters but except (-) . Give me any idea.

我们有一个文本字段。我们知道如何限制特殊字符。但我们只需要允许字母和数字和连字符 (-)。不需要特殊字符,但 (-) 除外。给我任何想法。

Mycode:

我的代码:

$('#pduration').keydown(function (e) {
           if (e.shiftKey || e.ctrlKey || e.altKey) {
                e.preventDefault();
            } else {
               var key = e.keyCode;
               if (keyCodeEntered == 45) {
                   // Allow only 1 minus sign ('-')...
                  if ((elementRef.value) && (elementRef.value.indexOf('-') >= 0))
                       return false;
                   else
                       return true;
               }

           }
       });

If we tried this code it's restrict spectal charecters but it's allow -,/,+ Please guide me only allow number and alphabet and hyphen only

如果我们尝试此代码,它会限制特殊字符,但允许 -,/,+ 请指导我只允许数字和字母和连字符

采纳答案by qtgye

replace this section:

替换此部分:

if (keyCodeEntered == 45) {
// Allow only 1 minus sign ('-')...
if ((elementRef.value) && (elementRef.value.indexOf('-') >= 0))
       return false;
{
else
     return true;
}

with this:

有了这个:

 //         keys a-z,0-9               numpad keys 0-9            minus sign    backspace
if ( ( key >= 48 && key <= 90 ) || ( key >= 96 && key <= 105 )  || key == 109 || key==8)
{
    //return true;
}
else
{
    //return false
}
})

回答by xiix

It's quite easy to do with regex pattern matching.

使用正则表达式模式匹配非常容易。

For JavaScript I recommend https://regex101.com/, and for regex in general i recommend Rubular for testing and learning.

对于 JavaScript,我推荐https://regex101.com/,对于正则表达式,我推荐使用 Rubular 进行测试和学习。

A Regex pattern consists looks like this:

正则表达式模式如下所示:

/pattern/flags

**First, declare a regex pattern*

**首先,声明一个正则表达式模式*

/<regex here>/

In order to capture only certain types of characters, we'll use character classes.

为了仅捕获某些类型的字符,我们将使用字符类。

/[<char class here]/

Then use this class to match first lowercase letter, first uppercase letter, first number or first "-" character.

然后使用这个类来匹配第一个小写字母、第一个大写字母、第一个数字或第一个“-”字符。

/[a-zA-Z0-9-]/

This will only catch the first character

这只会捕获第一个字符

Since we want all matching characters, we add the flag gfor global, which will return allthe characters that match. A final pattern for getting all legalflags loosk like this:

由于我们想要所有匹配的字符,我们gglobal添加了标志,它将返回所有匹配的字符。获取所有合法标志的最终模式如下所示:

/[a-zA-Z0-9-]/g

That's it for the pattern.

这就是模式。

In order to check if something contains illegal characters, like you asked, you can do something like this (both examples work):

为了检查某些内容是否包含非法字符,如您所问,您可以执行以下操作(两个示例都有效):

function verifyIllegalCharacters (inputString) 
{
    // Copy the results from replace to new string
    // It now holds the original string, minus all legal characters.
    // Since they were overwritten by "".
    var newStr = inputString.replace(/[a-zA-Z0-9-]/g, "");

    // If length is 0, all legal characters were removed, 
    // and no illegal characters remain. 
    return (newStr.length == 0);
}

function verifyIllegalCharacters (inputString) 
{
    // Same, but here we instead check for characters
    // NOT matching the pattern. Above we capture all legal chars,
    // here we capture all illegal chars by adding a ^ inside the class,
    // And overwrite them with "".
    var newStr = inputString.replace(/[^a-zA-Z0-9-]/g, "");

    // If the lengths aren't equal, something was removed
    // If something was removed, the string contained illegal chars.
    // Returns true if no illegal chars, else false.
    return (newStr.length == inputString.length);
}