Šime Vidas
Šime Vidas

Reputation: 185973

Reading <input> values as numbers and not strings (JavaScript)

Let's assume we have a text-box on the page:

<input type="text">  

The visitor types in some characters, and we read those characters via the value property of the text-box.

Now, let's say that the text-box represents a numeric value. I cannot define such a thing on the text-box - its value is always going to be a string value. What I can do is, convert that sting value into a numeric value:

Number(input.value)

However, the input value is treated as a StringNumericLiteral, and not a NumericLiteral. That means that these input values are allowed (although they are not numeric literals in JavaScript):

Now, let us say that - for the sake of the argument - I really want to read the input value as NumericLiteral. I don't want numbers with leading zeros or the + sign, etc. I was thinking how I could accomplish this, and this is what I came up with:

try  {                  
    var n = JSON.parse('{ "n": ' + this.value + ' }').n;
    if (typeof n !== "number") {
        throw "error";
    }
    // n is a Number value that represents the value of the text-box        
} catch(e) {}

This is a simplified version of the code, a live demo is available here:
http://vidasp.net/tinydemos/input-as-number.html

Note: I use try-catch because if the input value is not a valid JSON value, the JSON.parse call will fail (throw an error).

So, what do you think of this method. Does it have flaws?

(One downside is that hex numeric values cannot be read, because JSON does not allow them.)

I just realized ...

... that the reason why I was trying to do this was not to actually read the input as a number. What I wanted is to check whether the value complied to the NumericLiteral grammar - which is something that a regexp check can do easily.

Upvotes: 0

Views: 3966

Answers (1)

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827724

With JSON.parse you will be processing your value as a JSONNumber token, not really as a NumericLiteral.

There are differences between JSONNumber and NumericLiteral, JSONNumber doesn't allow leading zeros (no octals), nor hexadecimal literals, nor a leading dot (3.), or the opposite, a dot followed by the fraction digits (.3), moreover JSON.parse is really buggy across implementations, regarding numeric values, in SpiderMonkey (and in the json2.js library) JSON.parse('01') will not throw as one can expect.

You could do validation to ensure the string complies with the NumericLiteral grammar, and if it does, you can use either eval or the Function constructor to really convert your value, for example:

var numericLiteral = (function () {
  var numericLiteralSyntax = new RegExp([
    '^0x[\\da-fA-F]+$', // HexIntegerLiteral
    '^0[0-7]+$',        // OctalIntegerLiteral
    '^(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)(?:[eE][+-]?\\d+)?$'//DecimalLiteral
  ].join('|'));

  return function (value) {
    if (typeof value != 'string') { throw TypeError('value must be a String'); }

    if (numericLiteralSyntax.test(value)) {
      return Function('return ' + value)(); // a NumericLiteral, evaluate it
    }
    throw SyntaxError('Invalid NumericLiteral'); // Not a NumericLiteral
  }
})();

numericLiteral('0xFF'); // 255, an HexIntegerLiteral
numericLiteral('2e1'); // 20, DecimalLiteral with ExponentPart
numericLiteral('3.'); // 3
numericLiteral('.3'); // 0.3
numericLiteral('3.1416'); // 3.1416
numericLiteral('00010'); // 8, an OctalIntegerLiteral

RegExps for validation are from SourceText a JavaScript Utility by Asen Bozhilov.

Upvotes: 4

Related Questions