javascript检查输入字符串是否包含数字

发布于 2024-11-03 15:14:45 字数 32 浏览 4 评论 0原文

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

My end goal is to validate an input field. The input may be either alphabetic or numeric.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

不喜欢何必死缠烂打 2024-11-10 15:14:47

您还可以尝试 lodash:

const isNumeric = number => 
  _.isFinite(_.parseInt(number)) && !_.isNaN(_.parseInt(number))

You can also try lodash:

const isNumeric = number => 
  _.isFinite(_.parseInt(number)) && !_.isNaN(_.parseInt(number))
伏妖词 2024-11-10 15:14:46

如果我没记错的话,问题需要“包含数字”,而不是“是数字”。所以:

function hasNumber(myString) {
  return /\d/.test(myString);
}

If I'm not mistaken, the question requires "contains number", not "is number". So:

function hasNumber(myString) {
  return /\d/.test(myString);
}
完美的未来在梦里 2024-11-10 15:14:46

您可以使用 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');
}

You can do this using javascript. No need for Jquery or Regex

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

While implementing

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

Update: To check if a string has numbers in them, you can use regular expressions to do that

var matches = val.match(/\d+/g);
if (matches != null) {
    alert('number');
}
じ违心 2024-11-10 15:14:46

这就是你所需要的。

      var hasNumber = /\d/;   
      hasNumber.test("ABC33SDF");  //true
      hasNumber.test("ABCSDF");  //false 

This is what you need.

      var hasNumber = /\d/;   
      hasNumber.test("ABC33SDF");  //true
      hasNumber.test("ABCSDF");  //false 
伏妖词 2024-11-10 15:14:46
function validate(){    
    var re = /^[A-Za-z]+$/;
    if(re.test(document.getElementById("textboxID").value))
       alert('Valid Name.');
    else
       alert('Invalid Name.');      
}
function validate(){    
    var re = /^[A-Za-z]+$/;
    if(re.test(document.getElementById("textboxID").value))
       alert('Valid Name.');
    else
       alert('Invalid Name.');      
}
涫野音 2024-11-10 15:14:46

无论如何,它都不是防弹的,但它符合我的目的,也许会对某人有所帮助。

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

It's not bulletproof by any means, but it worked for my purposes and maybe it will help someone.

var value = $('input').val();
 if(parseInt(value)) {
  console.log(value+" is a number.");
 }
 else {
  console.log(value+" is NaN.");
 }
你不是我要的菜∠ 2024-11-10 15:14:46

使用JavaScript 正则表达式。正则表达式是用于描述搜索模式的特殊文本字符串,以 /pattern/modifiers 的形式编写,其中“pattern”是正则表达式本身,“modifiers”是一系列指示各种选项的字符。

        字符class 是字面匹配之后最基本的正则表达式概念。它使一小段字符序列与一大组字符相匹配。例如,[AZ] 可以代表大写字母,\d 可以表示任何数字。

在下面的示例中

  • contains_alphaNumeric « 它检查字符串是否包含字母或数字(或)同时包含字母和数字。 连字符 (-) 会被忽略
  • onlyMixOfAlphaNumeric « 它检查字符串是否仅包含任何序列顺序的字母和数字

示例:

function matchExpression( str ) {
    var rgularExp = {
        contains_alphaNumeric : /^(?!-)(?!.*-)[A-Za-z0-9-]+(?<!-)$/,
        containsNumber : /\d+/,
        containsAlphabet : /[a-zA-Z]/,

        onlyLetters : /^[A-Za-z]+$/,
        onlyNumbers : /^[0-9]+$/,
        onlyMixOfAlphaNumeric : /^([0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*$/
    }

    var expMatch = {};
    expMatch.containsNumber = rgularExp.containsNumber.test(str);
    expMatch.containsAlphabet = rgularExp.containsAlphabet.test(str);
    expMatch.alphaNumeric = rgularExp.contains_alphaNumeric.test(str);

    expMatch.onlyNumbers = rgularExp.onlyNumbers.test(str);
    expMatch.onlyLetters = rgularExp.onlyLetters.test(str);
    expMatch.mixOfAlphaNumeric = rgularExp.onlyMixOfAlphaNumeric.test(str);

    return expMatch;
}

// HTML Element attribute's[id, name] with dynamic values.
var id1 = "Yash", id2="777", id3= "Yash777", id4= "Yash777Image4"
    id11= "image5.64", id22= "55-5.6", id33= "image_Yash", id44= "image-Yash"
    id12= "_-.";
console.log( "Only Letters:\n ", matchExpression(id1) );
console.log( "Only Numbers:\n ", matchExpression(id2) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id3) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id4) );

console.log( "Mixed with Special symbols" );
console.log( "Letters and Numbers :\n ", matchExpression(id11) );
console.log( "Numbers [-]:\n ", matchExpression(id22) );
console.log( "Letters :\n ", matchExpression(id33) );
console.log( "Letters [-]:\n ", matchExpression(id44) );

console.log( "Only Special symbols :\n ", matchExpression(id12) );

输出:

Only Letters:
  {containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: true, mixOfAlphaNumeric: false}
Only Numbers:
  {containsNumber: true, containsAlphabet: false, alphaNumeric: true, onlyNumbers: true, onlyLetters: false, mixOfAlphaNumeric: false}
Only Mix of Letters and Numbers:
  {containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Only Mix of Letters and Numbers:
  {containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Mixed with Special symbols
Letters and Numbers :
  {containsNumber: true, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Numbers [-]:
  {containsNumber: true, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters :
  {containsNumber: false, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters [-]:
  {containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Only Special symbols :
  {containsNumber: false, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}

java 模式匹配与正则表达式。

Using Regular Expressions with JavaScript. A regular expression is a special text string for describing a search pattern, which is written in the form of /pattern/modifiers where "pattern" is the regular expression itself, and "modifiers" are a series of characters indicating various options.

         The character class is the most basic regex concept after a literal match. It makes one small sequence of characters match a larger set of characters. For example, [A-Z] could stand for the upper case alphabet, and \d could mean any digit.

From below example

  • contains_alphaNumeric « It checks for string contains either letter or number (or) both letter and number. The hyphen (-) is ignored.
  • onlyMixOfAlphaNumeric « It checks for string contain both letters and numbers only of any sequence order.

Example:

function matchExpression( str ) {
    var rgularExp = {
        contains_alphaNumeric : /^(?!-)(?!.*-)[A-Za-z0-9-]+(?<!-)$/,
        containsNumber : /\d+/,
        containsAlphabet : /[a-zA-Z]/,

        onlyLetters : /^[A-Za-z]+$/,
        onlyNumbers : /^[0-9]+$/,
        onlyMixOfAlphaNumeric : /^([0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*$/
    }

    var expMatch = {};
    expMatch.containsNumber = rgularExp.containsNumber.test(str);
    expMatch.containsAlphabet = rgularExp.containsAlphabet.test(str);
    expMatch.alphaNumeric = rgularExp.contains_alphaNumeric.test(str);

    expMatch.onlyNumbers = rgularExp.onlyNumbers.test(str);
    expMatch.onlyLetters = rgularExp.onlyLetters.test(str);
    expMatch.mixOfAlphaNumeric = rgularExp.onlyMixOfAlphaNumeric.test(str);

    return expMatch;
}

// HTML Element attribute's[id, name] with dynamic values.
var id1 = "Yash", id2="777", id3= "Yash777", id4= "Yash777Image4"
    id11= "image5.64", id22= "55-5.6", id33= "image_Yash", id44= "image-Yash"
    id12= "_-.";
console.log( "Only Letters:\n ", matchExpression(id1) );
console.log( "Only Numbers:\n ", matchExpression(id2) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id3) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id4) );

console.log( "Mixed with Special symbols" );
console.log( "Letters and Numbers :\n ", matchExpression(id11) );
console.log( "Numbers [-]:\n ", matchExpression(id22) );
console.log( "Letters :\n ", matchExpression(id33) );
console.log( "Letters [-]:\n ", matchExpression(id44) );

console.log( "Only Special symbols :\n ", matchExpression(id12) );

Out put:

Only Letters:
  {containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: true, mixOfAlphaNumeric: false}
Only Numbers:
  {containsNumber: true, containsAlphabet: false, alphaNumeric: true, onlyNumbers: true, onlyLetters: false, mixOfAlphaNumeric: false}
Only Mix of Letters and Numbers:
  {containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Only Mix of Letters and Numbers:
  {containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Mixed with Special symbols
Letters and Numbers :
  {containsNumber: true, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Numbers [-]:
  {containsNumber: true, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters :
  {containsNumber: false, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters [-]:
  {containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Only Special symbols :
  {containsNumber: false, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}

java Pattern Matching with Regular Expressions.

缪败 2024-11-10 15:14:46

您可以使用 JavaScript 来完成此操作。不需要 Jquery 或 Regex

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

You can do this using javascript. No need for Jquery or Regex

function isNumeric(n) 
{
  return !isNaN(n);
}
单调的奢华 2024-11-10 15:14:46

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

const s = "EMA618"

function hasInt(me){
  let i = 1,a = me.split(""),b = "",c = "";
  a.forEach(function(e){
   if (!isNaN(e)){
     console.log(`CONTAIN NUMBER «${e}» AT POSITION ${a.indexOf(e)} => TOTAL COUNT ${i}`)
     c += e
     i++
   } else {b += e}
  })
  console.log(`STRING IS «${b}», NUMBER IS «${c}»`)
  if (i === 0){
    return false
    // return b
  } else {
    return true
    // return +c
  }
}


hasInt(s)

To test if any char is a number, without overkill❓, to be adapted as need.

const s = "EMA618"

function hasInt(me){
  let i = 1,a = me.split(""),b = "",c = "";
  a.forEach(function(e){
   if (!isNaN(e)){
     console.log(`CONTAIN NUMBER «${e}» AT POSITION ${a.indexOf(e)} => TOTAL COUNT ${i}`)
     c += e
     i++
   } else {b += e}
  })
  console.log(`STRING IS «${b}», NUMBER IS «${c}»`)
  if (i === 0){
    return false
    // return b
  } else {
    return true
    // return +c
  }
}


hasInt(s)

山色无中 2024-11-10 15:14:46

检查它的一种方法是循环遍历字符串并在输入数字时返回 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;
        }
    }
}

One way to check it is to loop through the string and return true (or false depending on what you want) when you hit a number.

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;
        }
    }
}
后知后觉 2024-11-10 15:14:46

当字符串以整数表示形式开头时,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。

parseInt provides integers when the string begins with the representation of an integer:

(parseInt '1a')  is  1

..so perhaps:

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

Pardon my CoffeeScript.

你对谁都笑 2024-11-10 15:14:46

我认为这是提取数字和字符串的简单方法。

str = "jdghj4874y6jfngvjbng"
let num = []
let strEx = []
for (i = 0; i < str.length; i++) {
  if (str[i] >= 0) {
    num.push(str[i])
  } else {
    strEx.push(str[i])
  }
}
console.log('nums:', JSON.stringify(num))
console.log('chars:', JSON.stringify(strEx))

I think it's simple and easy way to extract numbers and string.

str = "jdghj4874y6jfngvjbng"
let num = []
let strEx = []
for (i = 0; i < str.length; i++) {
  if (str[i] >= 0) {
    num.push(str[i])
  } else {
    strEx.push(str[i])
  }
}
console.log('nums:', JSON.stringify(num))
console.log('chars:', JSON.stringify(strEx))

緦唸λ蓇 2024-11-10 15:14:46
function check_string(str){
  const number_pattern = /\d/;
  return number_pattern.test(str)
}

let sample_string = "Hello World 1234";
let is_string_contains_number = check_string(sample_string);
//output : true [if the string contains number in it]
function check_string(str){
  const number_pattern = /\d/;
  return number_pattern.test(str)
}

let sample_string = "Hello World 1234";
let is_string_contains_number = check_string(sample_string);
//output : true [if the string contains number in it]
那请放手 2024-11-10 15:14:46

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

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

This code also helps in, "To Detect Numbers in Given String" when numbers found it stops its execution.

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_;
}
满天都是小星星 2024-11-10 15:14:46

下面的代码检查相同的数字、序列号和相反的数字序列。

function checkNumSequnce(arrayNM2) {
    inseqCounter=1;
    continousSeq = 1;
    decsequenceConter = 1;
    var isequence = true;
    for (i=0;i<arrayNM2.length-1;i++) {
      j=i+1;
      if (arrayNM2[i] == arrayNM2[i+1]) { 
                if(inseqCounter > 1 || decsequenceConter > 1){
                    isequence =  false; break;
                }        
                 continousSeq++; 
                             
         }         
        else if (arrayNM2[j]- arrayNM2[i] == 1) {
            if(decsequenceConter > 1 || continousSeq > 1){
                isequence =  false; break;  
              }      
             inseqCounter++;               
                        
        } else if(arrayNM2[i]- arrayNM2[j] == 1){
              if(inseqCounter > 1 || continousSeq > 1){
                   isequence =  false; break;
               }
              decsequenceConter++;
        }else{
              isequence= false;
              break;
        }
  };

  console.log("isequence: "+ isequence); 

  };

Below code checks for same number, sequence number and reverse number sequence.

function checkNumSequnce(arrayNM2) {
    inseqCounter=1;
    continousSeq = 1;
    decsequenceConter = 1;
    var isequence = true;
    for (i=0;i<arrayNM2.length-1;i++) {
      j=i+1;
      if (arrayNM2[i] == arrayNM2[i+1]) { 
                if(inseqCounter > 1 || decsequenceConter > 1){
                    isequence =  false; break;
                }        
                 continousSeq++; 
                             
         }         
        else if (arrayNM2[j]- arrayNM2[i] == 1) {
            if(decsequenceConter > 1 || continousSeq > 1){
                isequence =  false; break;  
              }      
             inseqCounter++;               
                        
        } else if(arrayNM2[i]- arrayNM2[j] == 1){
              if(inseqCounter > 1 || continousSeq > 1){
                   isequence =  false; break;
               }
              decsequenceConter++;
        }else{
              isequence= false;
              break;
        }
  };

  console.log("isequence: "+ isequence); 

  };
兲鉂ぱ嘚淚 2024-11-10 15:14:46

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

function handleValueChange() {
  if (!/[^a-zA-Z]/.test(document.getElementById('textbox_id').value)) {
      var x = document.getElementById('result');
      x.innerHTML = 'String does not contain number';
  } else {
    var x = document.getElementById('result');
    x.innerHTML = 'String does contains number';
  }
}
input {
  padding: 5px;
}
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>

We can check it by using !/[^a-zA-Z]/.test(e)
Just run snippet and check.

function handleValueChange() {
  if (!/[^a-zA-Z]/.test(document.getElementById('textbox_id').value)) {
      var x = document.getElementById('result');
      x.innerHTML = 'String does not contain number';
  } else {
    var x = document.getElementById('result');
    x.innerHTML = 'String does contains number';
  }
}
input {
  padding: 5px;
}
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>

给妤﹃绝世温柔 2024-11-10 15:14:46

没有人解决问题的正文:

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

-- 操作

所以这是一个返回布尔值答案的函数,
true 如果传递的输入具有数字值或严格字母字符串值,
false 否则:

const isAlphaOrNumeric = input => {
  if ('' === input.value.trim())
    return false // empty
    
  if (!Number.isNaN(Number(input.value)))
    return true //'number'

  return /^[a-zA-Z]+$/.test(input.value.trim()) // 'alphabetic'
}

const isAlphaOrNumeric = input => {
  if ('' === input.value.trim())
    return false

  if (!Number.isNaN(Number(input.value)))
    return true

  return /^[a-zA-Z]+$/.test(input.value.trim())
}

const f = document.querySelector('form')
const test = f.querySelector('[name="test"]')
const test2 = f.querySelector('[name="test2"]')
const test3 = f.querySelector('[name="test3"]')
f.onsubmit = e => {
  e.preventDefault()
  console.log(test.value, isAlphaOrNumeric(test))
  console.log(test2.value, isAlphaOrNumeric(test2))
  console.log(test3.value, isAlphaOrNumeric(test3))
}
<form>
  <input name="test" value="abc"><br>
  <input name="test2" value="-3.14"><br>
  <input name="test3" value="AFF4B3"><br>
  <button>
    check it
  </button>
</form>

Nobody has addressed the body of the question:

My end goal is to validate an input field. The input may be either alphabetic or numeric.

-- op

So here is a function that returns a boolean answer,
true if the passed input has a Number value OR a strictly alphabetic string value,
false otherwise:

const isAlphaOrNumeric = input => {
  if ('' === input.value.trim())
    return false // empty
    
  if (!Number.isNaN(Number(input.value)))
    return true //'number'

  return /^[a-zA-Z]+$/.test(input.value.trim()) // 'alphabetic'
}

const isAlphaOrNumeric = input => {
  if ('' === input.value.trim())
    return false

  if (!Number.isNaN(Number(input.value)))
    return true

  return /^[a-zA-Z]+$/.test(input.value.trim())
}

const f = document.querySelector('form')
const test = f.querySelector('[name="test"]')
const test2 = f.querySelector('[name="test2"]')
const test3 = f.querySelector('[name="test3"]')
f.onsubmit = e => {
  e.preventDefault()
  console.log(test.value, isAlphaOrNumeric(test))
  console.log(test2.value, isAlphaOrNumeric(test2))
  console.log(test3.value, isAlphaOrNumeric(test3))
}
<form>
  <input name="test" value="abc"><br>
  <input name="test2" value="-3.14"><br>
  <input name="test3" value="AFF4B3"><br>
  <button>
    check it
  </button>
</form>

暖风昔人 2024-11-10 15:14:46

尝试这个来检查字符串是否有数字。

'test123'.split('').reduce((result,ch) => ch.charCodeAt(0) >= 48 && ch.charCodeAt(0) <= 57), false);

Try this to check whether string has number or not.

'test123'.split('').reduce((result,ch) => ch.charCodeAt(0) >= 48 && ch.charCodeAt(0) <= 57), false);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文