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


当前回答

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

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

其他回答

检查它的一种方法是遍历字符串并在命中数字时返回true(或false,这取决于您想要什么)。

function checkStringForNumbers(input){
    let str = String(input);
    for( let i = 0; i < str.length; i++){
              console.log(str.charAt(i));
        if(!isNaN(str.charAt(i))){           //if the string is a number, do the following
            return true;
        }
    }
}
function validate(){    
    var re = /^[A-Za-z]+$/;
    if(re.test(document.getElementById("textboxID").value))
       alert('Valid Name.');
    else
       alert('Invalid Name.');      
}

要测试任何字符是否为数字,无需过度修饰❓,可根据需要进行调整。

const s = "EMA618" 函数hasInt(我){ 设I = 1,a = me.split(""),b = "",c = ""; a.forEach(函数(e) { 如果(! isNaN (e)) { console.log(' contains NUMBER«${e}»AT POSITION ${a.indexOf(e)} => TOTAL COUNT ${i} ') C += e 我+ + } else {b += e} }) console.log('字符串是«${b}»,数字是«${c}»') If (i === 0){ 返回假 //返回b }其他{ 还真 //返回+c } } hasInt (s)

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

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

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

function isNumeric(n) 
{
  return !isNaN(n);
}