JavaScript中检查字母数字的最佳方法

188

JSP 中,执行对 INPUT 字段进行字母数字检查的最佳方法是什么?我附上了我的当前代码。

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;
}


4
取决于你如何定义“最佳”。下面的大多数答案建议使用正则表达式,但其性能比你原来的代码慢得多。我稍微整理了一下你的代码,它实际上表现得非常好。 - Michael Martin-Smucker
15个回答

3
如果你想要一个最简单的一行解决方案,那么使用正则表达式的接受的答案就可以了。
然而,如果你想要一个更快的解决方案,那么这里有一个函数供您使用。

console.log(isAlphaNumeric('a')); // true
console.log(isAlphaNumericString('HelloWorld96')); // true
console.log(isAlphaNumericString('Hello World!')); // false

/**
 * Function to check if a character is alpha-numeric.
 *
 * @param {string} c
 * @return {boolean}
 */
function isAlphaNumeric(c) {
  const CHAR_CODE_A = 65;
  const CHAR_CODE_Z = 90;
  const CHAR_CODE_AS = 97;
  const CHAR_CODE_ZS = 122;
  const CHAR_CODE_0 = 48;
  const CHAR_CODE_9 = 57;

  let code = c.charCodeAt(0);

  if (
    (code >= CHAR_CODE_A && code <= CHAR_CODE_Z) ||
    (code >= CHAR_CODE_AS && code <= CHAR_CODE_ZS) ||
    (code >= CHAR_CODE_0 && code <= CHAR_CODE_9)
  ) {
    return true;
  }

  return false;
}

/**
 * Function to check if a string is fully alpha-numeric.
 *
 * @param {string} s
 * @returns {boolean}
 */
function isAlphaNumericString(s) {
  for (let i = 0; i < s.length; i++) {
    if (!isAlphaNumeric(s[i])) {
      return false;
    }
  }

  return true;
}


2
const isAlphaNumeric = (str) => {

  let n1 = false,
    n2 = false;
  const myBigBrainString =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  const myHackyNumbers = "0123456789";

  for (let i = 0; i < str.length; i++) {
    if (myBigBrainString.indexOf(str.charAt(i)) >= 0) {
      n1 = true;
    }
    if (myHackyNumbers.indexOf(str.charAt(i)) >= 0) {
      n2 = true;
    }

    if (n1 && n2) {
      return true;
    }
  }

  return n1 && n2;
};

持续运行至永恒...


2
(/[^0-9a-zA-Z]/.test( "abcdeFGh123456" ));

1

移除了字母数字验证中的NOT操作。将变量移动到块级作用域。这里和那里有一些注释。派生自最佳Micheal

function isAlphaNumeric ( str ) {

  /* Iterating character by character to get ASCII code for each character */
  for ( let i = 0, len = str.length, code = 0; i < len; ++i ) {

    /* Collecting charCode from i index value in a string */
    code = str.charCodeAt( i ); 

    /* Validating charCode falls into anyone category */
    if (
        ( code > 47 && code < 58) // numeric (0-9)
        || ( code > 64 && code < 91) // upper alpha (A-Z)
        || ( code > 96 && code < 123 ) // lower alpha (a-z)
    ) {
      continue;
    } 

    /* If nothing satisfies then returning false */
    return false
  }

  /* After validating all the characters and we returning success message*/
  return true;
};

console.log(isAlphaNumeric("oye"));
console.log(isAlphaNumeric("oye123"));
console.log(isAlphaNumeric("oye%123"));


0

string 转换为字母数字(在文件名的情况下很有用)

function stringToAlphanumeric(str = ``) {
  return str
    .split('')
    .map((e) => (/^[a-z0-9]+$/i.test(e) ? e : '_'))
    .join('')
}

const fileName = stringToAlphanumeric(`correct-('"é'è-///*$##~~*\\\"filename`)
console.log(fileName)
// expected  output "correct_filename"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接