在 Javascript 中进行字母数字检查的最佳方法

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

Best way to alphanumeric check in Javascript

javascriptvalidation

提问by t0mcat

Can you please suggest the best possible way to perform an alpha numeric check on an INPUT field in JSP? I have attached my current code and I know its no where close to perfect :)

您能否建议对 JSP 中的 INPUT 字段执行字母数字检查的最佳方法?我附上了我当前的代码,我知道它没有接近完美的地方:)

<script type="text/javascript">
  function validateCode(){
      var TCode = document.getElementById('TCode').value;
      for(var i=0; i<TCode.length; i++)
      {
        var char1 = TCode.charAt(i);
        var cc = char1.charCodeAt(0);

        if((cc>47 && cc<58) || (cc>64 && cc<91) || (cc>96 && cc<123))
        {

        }
         else {
         alert('Input is not alphanumeric');
         return false;
         }
      }
     return true;     
   }

采纳答案by Mahesh Velaga

You can use this regex/^[a-z0-9]+$/i

您可以使用此正则表达式/^[a-z0-9]+$/i

回答by Michael Martin-Smucker

The asker's original inclination to use str.charCodeAt(i)appears to be faster than the regular expression alternative. In my test on jsPerfthe RegExp option performs 66% slower in Chrome 36 (and slightly slower in Firefox 31).

提问者最初倾向于使用str.charCodeAt(i)似乎比正则表达式替代方案更快。在我对 jsPerf测试中,RegExp 选项在 Chrome 36 中的执行速度慢 66%(在 Firefox 31 中稍慢)。

Here's a cleaned-up version of the original validation code that receives a string and returns trueor false:

这是原始验证代码的清理版本,它接收一个字符串并返回trueor false

function isAlphaNumeric(str) {
  var code, i, len;

  for (i = 0, len = str.length; i < len; i++) {
    code = str.charCodeAt(i);
    if (!(code > 47 && code < 58) && // numeric (0-9)
        !(code > 64 && code < 91) && // upper alpha (A-Z)
        !(code > 96 && code < 123)) { // lower alpha (a-z)
      return false;
    }
  }
  return true;
};

Of course, there may be other considerations, such as readability. A one-line regular expression is definitely prettier to look at. But if you're strictly concerned with speed, you may want to consider this alternative.

当然,可能还有其他的考虑,比如可读性。单行正则表达式肯定更漂亮。但是,如果您严格关注速度,则可能需要考虑这种替代方案。

回答by Mischa Arefiev

Check it with a regex.

用正则表达式检查它。

Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:

Javascript regexen 没有 POSIX 字符类,因此您必须手动编写字符范围:

if (!input_string.match(/^[0-9a-z]+$/))
  show_error_or_something()

Here ^means beginning of string and $means end of string, and [0-9a-z]+means one or more of character from 0to 9OR from ato z.

这里^表示字符串的开始,表示字符串的$结束,[0-9a-z]+表示一个或多个字符 from 0to 9OR from ato z

More information on Javascript regexen here: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

有关 Javascript regexen 的更多信息,请访问:https: //developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

回答by user113716

You don't need to do it one at a time. Just do a test for any that are notalpha-numeric. If one is found, the validation fails.

你不需要一次做一个。只需对不是字母数字的任何内容进行测试。如果找到,则验证失败。

function validateCode(){
    var TCode = document.getElementById('TCode').value;
    if( /[^a-zA-Z0-9]/.test( TCode ) ) {
       alert('Input is not alphanumeric');
       return false;
    }
    return true;     
 }

If there's at least one match of a non alpha numeric, it will return false.

如果至少有一个非字母数字的匹配项,它将return false.

回答by Justin

I would create a String prototype method:

我会创建一个字符串原型方法:

String.prototype.isAlphaNumeric = function() {
  var regExp = /^[A-Za-z0-9]+$/;
  return (this.match(regExp));
};

Then, the usage would be:

然后,用法将是:

var TCode = document.getElementById('TCode').value;
return TCode.isAlphaNumeric()

回答by Neerajan

    // On keypress event call the following method
    function AlphaNumCheck(e) {
        var charCode = (e.which) ? e.which : e.keyCode;
        if (charCode == 8) return true;

        var keynum;
        var keychar;
        var charcheck = /[a-zA-Z0-9]/;
        if (window.event) // IE
        {
            keynum = e.keyCode;
        }
        else {
            if (e.which) // Netscape/Firefox/Opera
            {
                keynum = e.which;
            }
            else return true;
        }

        keychar = String.fromCharCode(keynum);
        return charcheck.test(keychar);
    }

Further, this articlealso helps to understand JavaScript alphanumeric validation.

此外,本文还有助于理解 JavaScript 字母数字验证。

回答by Malganis

In a tight loop, it's probably better to avoid regex and hardcode your characters:

在一个紧凑的循环中,最好避免使用正则表达式并对字符进行硬编码:

const CHARS = new Set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
function isAlphanumeric(char) {
    return CHARS.has(char);
}

回答by Oscar Zarrus

Excuse me all, no controversy. But for the community to grow as it has grown me in these years, it is good to make some notes.

恕我直言,没有争议。但是为了让社区像这些年来我一样成长,做一些笔记是很好的。

The real alphanumeric string is like "0a0a0a0b0c0d"and not like "000000"or "qwertyuio".

真正的字母数字字符串是 like"0a0a0a0b0c0d"和 not like "000000"or "qwertyuio"

All the answers I read here, returned truein both cases. And forgive me, IMHO, this is not right.

我在这里读到的所有答案,true在这两种情况下都返回了。原谅我,恕我直言,这是不对的

If I want to check if my "00000"string is alphanum, my "human" answer is unquestionably FALSE.

如果我想检查我的"00000"字符串是否是字母数字,我的“人类”答案无疑是错误的。

Why? Simple. I cannot find any letter char. So, is a simple numeric string [0-9].

为什么?简单的。我找不到任何字母字符。所以,是一个简单的数字字符串[0-9]

On the other hand, if I wanted to check my "abcdefg"string, my "human" answer is even FALSE. I don't see numbers, so it's not alphanumeric. Just alpha [a-zA-Z].

另一方面,如果我想检查我的"abcdefg"字符串,我的“人类”答案甚至是错误的。我没有看到数字,所以它不是字母数字。只是阿尔法[a-zA-Z]

The Michael Martin-Smucker's answerhas been illuminating.

迈克尔·马丁-斯马克的答案已经被照亮。

However he was aimed at achieving better performance instead of regex. This is true, using a low level way there's a better perfomance. But results it's the same. The strings "0123456789"(only numeric), "qwertyuiop"(only alpha) and "0a1b2c3d4f4g"(alphanumeric) returns TRUEas alphanumeric. Same regex /^[a-z0-9]+$/iway. The reason why the regex does not work is as simple as obvious. The syntax []indicates or, not and. So, if is it only numeric orif is it only letters, regex returns true.

然而,他的目标是实现更好的性能而不是正则表达式。这是真的,使用低级别的方式有更好的性能。但结果是一样的。字符串"0123456789"(仅数字)、"qwertyuiop"(仅字母)和"0a1b2c3d4f4g"(字母数字)TRUE作为字母数字返回。相同的正则表达式/^[a-z0-9]+$/i方式。正则表达式不起作用的原因很简单。语法[]指示or, not and。因此,如果它只是数字只是字母,则正则表达式返回true.

But, the Michael Martin-Smucker's answerwas nevertheless illuminating. For me. It allowed me to think at "low level", to create a real function that unambiguous processes an alphanumeric string. I called it like PHP relative function ctype_alnum(edit 2020-02-18: Where, however, this checks OR and not AND).

但是,Michael Martin-Smucker 的回答仍然很有启发性。为了我。它让我能够在“低级”思考,创建一个真正的函数,明确处理字母数字字符串。我称它为 PHP 相关函数ctype_alnum编辑 2020-02-18:然而,这里检查 OR 而不是 AND)。

Here's the code:

这是代码:

function ctype_alnum(str) {
  var code, i, len;
    var isNumeric = false, isAlpha = false; //I assume that it is all non-alphanumeric



  for (i = 0, len = str.length; i < len; i++) {
    code = str.charCodeAt(i);


        switch (true){
            case code > 47 && code < 58: // check if 0-9
                isNumeric = true;
                break;
            case (code > 64 && code < 91) || (code > 96 && code < 123): //check if A-Z or a-z
                isAlpha = true;
                break;
            default: // not 0-9, not A-Z or a-z
                return false; //stop function with false result, no more checks

        }

  }

  return isNumeric && isAlpha; //return the loop results, if both are true, the string is certainly alphanumeric
};

... and here's the DEMO

...这是演示

I came to this discussion because I was looking for an alternative in javascript to the PHP function. I didn't find the answer "ready-to-go", but as often happens on Stackoverflow, the concept of knowledge and comparison with each other is something sublime, that leads you to think about someone's answerand find togetherthe solution you were looking for, but you didn't think you knew it.

我参加这个讨论是因为我在 javascript 中寻找 PHP 函数的替代方案。我没有找到“随时可用”的答案,但正如 Stackoverflow 上经常发生的那样,知识和相互比较的概念是崇高的,这会引导您思考某人的答案一起找到您的解决方案寻找,但你不认为你知道。

And share it!

并分享它!

Best

最好的事物

Oscar

奥斯卡

回答by Mark Baaijens

To check whether input_string is alphanumeric, simply use:

要检查 input_string 是否为字母数字,只需使用:

input_string.match(/[^\w]|_/) == null