我的最终目标是验证输入字段。输入可以是字母也可以是数字。


当前回答

当字符串以整数的表示形式开始时,parseInt提供整数:

(parseInt '1a')  is  1

..所以也许:

isInteger = (s)->
  s is (parseInt s).toString()  and  s isnt 'NaN'

(isInteger 'a') is false
(isInteger '1a') is false
(isInteger 'NaN') is false
(isInteger '-42') is true

原谅我的CoffeeScript。

其他回答

function validate(){    
    var re = /^[A-Za-z]+$/;
    if(re.test(document.getElementById("textboxID").value))
       alert('Valid Name.');
    else
       alert('Invalid Name.');      
}

无论如何,它都不是刀枪不入的,但它对我来说是有效的,也许它会帮助到别人。

var value = $('input').val();
 if(parseInt(value)) {
  console.log(value+" is a number.");
 }
 else {
  console.log(value+" is NaN.");
 }

我们可以使用!/[^a-zA-Z]/.test(e)来检查它。 只需运行snippet并检查。

handleValueChange() { 如果(! / [^ a-zA-Z] / test (. getelementbyid(“textbox_id”)value)) { var x = document.getElementById('result'); x.innerHTML = '字符串不包含数字'; }其他{ var x = document.getElementById('result'); x.innerHTML = 'String does contains number'; } } 输入{ 填充:5 px; } <input type="text" id="textbox_id" placeholder="Enter string here…" oninput="handleValueChange()" > < p id = "结果" > < / p >

你可以使用javascript来做到这一点。不需要Jquery或Regex

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

而实现

var val = $('yourinputelement').val();
if(isNumeric(val)) { alert('number'); } 
else { alert('not number'); }

更新:要检查字符串中是否有数字,可以使用正则表达式来检查

var matches = val.match(/\d+/g);
if (matches != null) {
    alert('number');
}

这段代码还有助于“检测给定字符串中的数字”,当发现数字时,它会停止执行。

function hasDigitFind(_str_) {
  this._code_ = 10;  /*When empty string found*/
  var _strArray = [];

  if (_str_ !== '' || _str_ !== undefined || _str_ !== null) {
    _strArray = _str_.split('');
    for(var i = 0; i < _strArray.length; i++) {
      if(!isNaN(parseInt(_strArray[i]))) {
        this._code_ = -1;
        break;
      } else {
        this._code_ = 1;
      }
    }

  }
  return this._code_;
}