0

To validate that the input field contains a numeric value I'm using the isNumeric() method of jQuery:

$.isNumeric(value);

This works fine for most of the cases, but the following example fails:

$.isNumeric("0.");

This returns true while it's not a numeric value.

Is there a better way of such validation without using any other plugin?

Thanks.

4
  • The argument can be of any type. api.jquery.com/jquery.isnumeric Commented Jan 14, 2015 at 19:18
  • It's likely parsing it Commented Jan 14, 2015 at 19:19
  • Do you want decimals too or just ints? Commented Jan 14, 2015 at 19:20
  • Decimals and integers. Commented Jan 14, 2015 at 19:25

4 Answers 4

1

You haven't listed all of your use cases, but I have ran through a couple in the console, including your breaking case;

You can simply cast the string to a JavaScript Number:

$.isNumeric(Number("0."))
=> true

And it seems to work with strings that aren't numbers as well.

$.isNumeric(Number("fasd"))
=> false

AMEND:

$.isNumeric(Number(0.))
=> true

$.isNumeric(Number(.0))
=> true

Also, if your DB doesn't like "0." then cast the thing:

Number(0.)
=> 0

Number(.0)
=> 0

Number(".0")
=> 0

Number("0.")
=> 0

Let me know if this solution doesn't cover your problem. Cheers!

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, but it doesn't. The data structure I'm storing the values in won't accept "0." or ".0" as valid numeric types so I want to prevent that.
Your question seems to ask how to query a string for Numeric status.
0

Try below code.

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

Example:

var matches = val.match(/\d+/g);
if (matches != null) {
    alert('number');
}

Comments

0

If what you want is to check the type, you can use jQuery.type():

console.log(jQuery.type( "0." ) === "number");// False
console.log(jQuery.type( 0. ) === "number");// True

Just for completeness, using this approach of type, you could check numbers this way:

var isNumber = function(o) {
    return typeof o === 'number' && isFinite(o);
}

BTW, 0. and .0 are valid number formats in javascript.

2 Comments

Nah, I'm looking for a generic way to validate numeric values - integers and decimals.
The data structure I'm storing the values in won't accept "0." or ".0" as valid numeric types so I want to prevent that.
0

The following is my solution:

!$.isNumeric(value) || value.substring(value.length - 1) == "." || value.substring(0, 1) == "."

If the result of this is false - the value is not numeric including 5. and .5 which are valid numeric values in JavaScript.

Thanks everybody for your input.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.