faqts : Computers : Programming : Languages : JavaScript : Language Core : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

77 of 101 people (76%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

How can I check whether a text field contains a number or not?
How can I check whether a string contains a valid number?
How can I check whether a string contains a valid number?

Mar 21st, 2000 07:46
Martin Honnen,


JavaScript 1.1+ (so every browser besides NN2 and IE3) has the top 
level function 
  isNaN
for that (it is also allegedly around in JavaScript 1.0 on unix but I 
can't check that).
So if you try
  isNaN('1.3')
it will return
  false
but
  isNaN('Kibo')
returns 
  true
That should suffice for elementary form field checking. 
There is also
  parseInt
and 
  parseFloat
but both check the beginning of a string for a valid integer/float and 
discard the rest of the string so while
  isNaN('1.3Kibo')
returns
  true
the expression
  parseFloat('1.3Kibo')
returns
  1.3
So parseInt/parseFloat are good for conversion but of limited use for 
number format checking.

Of course with JavaScript 1.2 the power of regular expressions is at 
your hands to do sophisticated pattern checks. For instance to check 
that a string contains nothing but digits
  var nonDigit = /\D/g;
  if (nonDigit.test('123'))
    // contains something else that a digit
  else
    // contains only digits