258

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

enjoylife
  • 3,801
  • 1
  • 24
  • 33
Udara S.S Liyanage
  • 6,189
  • 9
  • 33
  • 34
  • 6
    You don't need jQuery for that. – Šime Vidas Apr 25 '11 at 11:55
  • Please edit your question title, to something more accurate like "jQuery input validate only alphabetic characters" since your description leads to none answer on "how to find numbers in a string", therefore it results in an irrelevant search result for our community. Thanks! – Juanma Guerrero Aug 24 '12 at 16:53
  • Edited "jQuery" out of the question title, and replaced with "Javascript". – VKen Oct 13 '12 at 01:25
  • @VKen, It is not necessary to put tags on title. – Starx Oct 13 '12 at 02:28
  • @Starx noted, I'm just keeping the format the question poster started with. – VKen Oct 13 '12 at 02:35
  • ***For newcomers :*** The exact solution for this question is here =>https://stackoverflow.com/a/28813213/15823478 :) – shaderone Jun 25 '21 at 10:20

17 Answers17

490

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

function hasNumber(myString) {
  return /\d/.test(myString);
}
Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
Zon
  • 18,610
  • 7
  • 91
  • 99
  • this solution doesn't take into account non-integer numbers like 3.2 or 1e4 – ekkis Jan 12 '17 at 21:05
  • 13
    It does. Check in console: hasNumber("check 3.2 or 1e4") = true vs hasNumber("check no numbers") = false. Because 3.2 and 1e4 contain numbers in itself. – Zon Jan 17 '17 at 18:02
  • 2
    Why is this answer not on the top? – javaDeveloper Jul 16 '20 at 04:39
  • 2
    I tried putting the /\d/ in "" - that was stupid, just writing this in case someone else makes the same mistake – Chagai Friedlander Dec 02 '21 at 18:22
  • More information about the RegExp `.test` method can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test – joeljpa Feb 15 '23 at 05:43
129

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');
}
Starx
  • 77,474
  • 47
  • 185
  • 261
  • 3
    `matches != null` means not `undefined` or `null` while `matches !== null` means specifically not `null` but passes `undefined`. – Nate Nov 14 '14 at 14:33
  • `match()` returns an array or `null`. So `if (matches !== null)` should be fine (and it will please JSHint.) Source: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match – Jason Apr 24 '15 at 08:54
  • It should be `isFinite(parseFloat(n))` in the first example. `isNumeric("5,000")` fails. – m.spyratos Nov 15 '15 at 06:15
  • @m.spyratos, Well, `isFinite()` gives true if the passed value is a `finite` number and number `5,000` is a formatted string of number not a finite number. – Starx Nov 16 '15 at 19:41
  • @Starx, I agree. But if you don't support formatted string as input, then why do you use parse float in `isNaN`? I would suggest to either remove parse float from `isNaN` or add it to `isFinite` as well to be consisted. – m.spyratos Nov 18 '15 at 02:31
  • @m.spyratos, If you do a `parseFloat('5,000')` it will give `5` as a result, which truncates most of the actual data. Its not designed to extract numeric/float value from a string but to separate if possible like `parseFloat('50.65 %')` will actually give `50.65` as a result. So its just used to check if `parseFloat` return `NaN`. Using a double negative check of `NaN` with `isFinite` ensure the value passed is numeric hence the solutions. – Starx Nov 20 '15 at 19:31
  • @Starx, I don't exactly agree with your point that `5,000` should be treated differently than `50.65 %`, which actually both return `false` by the method. I found out though that this method is being used in the `_.isFinite` method of Underscore.js and the purpose of `parseFloat` in the `isNaN` is to avoid some inconsistencies of the javascript's `isFinite` (http://stackoverflow.com/a/27007535/1222409). Thanks! – m.spyratos Nov 22 '15 at 02:31
  • @m.spyratos, Yes, of course it returns false. I was explaining about `parseFloat()` not the solution itself. It doesn't treat them differently, hence return false for both. Thanks for link, I will give it a read. – Starx Nov 23 '15 at 09:49
  • @Starx, Thanks for explaining! – m.spyratos Nov 23 '15 at 16:46
  • For people not familiar with JavaScript regular expressions, you might want to explain what the regex is actually doing, particularly the trailing `g`. – Kevin Workman Jan 21 '16 at 18:07
  • This is not the answer since the title says **contains number** but this checks if the string is number. – Mohammad Kermani Nov 23 '17 at 09:02
  • There's no need for `+` in the regexp. Just matching 1 digit is enough. – Barmar Feb 03 '21 at 15:00
45

This is what you need.

      var hasNumber = /\d/;   
      hasNumber.test("ABC33SDF");  //true
      hasNumber.test("ABCSDF");  //false 
Usama Tahir
  • 1,235
  • 12
  • 14
23
function validate(){    
    var re = /^[A-Za-z]+$/;
    if(re.test(document.getElementById("textboxID").value))
       alert('Valid Name.');
    else
       alert('Invalid Name.');      
}
Jishnu A P
  • 14,202
  • 8
  • 40
  • 50
  • I had to read the whole question to realize this actually answers the exact question asked. The question title is a little deceptive. – Nate Nov 14 '14 at 14:31
11

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.");
 }
Jason D
  • 2,303
  • 14
  • 24
Elon Zito
  • 2,872
  • 1
  • 24
  • 28
9

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.

Yash
  • 9,250
  • 2
  • 69
  • 74
6

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

function isNumeric(n) 
{
  return !isNaN(n);
}
Jaime
  • 5,770
  • 4
  • 23
  • 50
user2164619
  • 85
  • 1
  • 1
  • 15
    Overkill. Could be just `function isNumeric(n) { return !isNaN(n); }` – Luca Steeb Jun 18 '15 at 16:58
  • 1
    This also doesn't check to see if ANY character is a number. But I can think of a solution inspired by this. – Tyler Lazenby Jan 29 '18 at 19:42
  • 1
    This only checks if it is a number, not if it contains a number. "ABC123" would resolve to false, whereas it should resolve to true. Also why create an extra function instead of just if ( !isNaN(str) ) {} ? – Sven Cazier Dec 08 '20 at 15:28
  • Working in TS in following way if (!isNaN(n)) { ...... } – Rajib Jul 27 '23 at 03:57
4

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)
NVRM
  • 11,480
  • 1
  • 88
  • 87
3

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;
        }
    }
}
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Herbert Su
  • 41
  • 3
1

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.

  • Basically, `parseInt('10m') /* returns 10*/` will do the trick **if** the string **starts** with a number. Otherwise returns NaN. If at all this behaviour is ok for you, consider `parseFloat('2.34million')` so you get 2.34 instead of losing money ;-) – mixdev Aug 10 '20 at 10:41
1

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))
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
sadiq shah
  • 11
  • 3
0

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_;
}
kusama
  • 389
  • 3
  • 13
0

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

  };
Kshitij
  • 360
  • 4
  • 12
  • 2
    This is undoubtedly the most confusing and verbose SO solution I have ever seen – Barris Jan 14 '21 at 12:39
  • @kshitij This is answer is working for sequential and repeated number validation. May be this answer is not 100% match for this question. But great logic. Thanks – Varun Sharma Feb 11 '21 at 12:49
0

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>
Rohit Tagadiya
  • 3,373
  • 1
  • 25
  • 25
  • 1
    this doesn't work for input `abc!` - the regex you have checks if its not an alphabet; this means even symbols like ! will be treated as number. – Chaitanya Bapat May 25 '22 at 10:08
0

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>
Arleigh Hix
  • 9,990
  • 1
  • 14
  • 31
0

Try this to check whether string has number or not.

'test123'.split('').reduce((result,ch) => ch.charCodeAt(0) >= 48 && ch.charCodeAt(0) <= 57), false);
RAKESH K
  • 61
  • 1
  • 5
-2

You can also try lodash:

const isNumeric = number => 
  _.isFinite(_.parseInt(number)) && !_.isNaN(_.parseInt(number))
Darex1991
  • 855
  • 1
  • 10
  • 24