Javascript isNumeric Function

in Javascript

When working with user inputs in web pages it is important that you validate all the inputs, this is so you can check that what the user is entering is the type of data you are expecting.

It is important to do both Server and client-side validation, if you just do server side validated then you are putting unnecessary work on the server for a task that can be done on the client side. but if you do the validation just on the client-side then this validation can be by-passed by simply turning off Javascript. This is why it's important to do both server side and client side validation.

But the problem is that these languages are different and have different functions, Javascript is missing a couple of the required functions needed to fully validate the user inputs.

In this example we are looking into client side validation which will validate numbers, so if we have an input for a number we want to make sure this data entered is in fact a number.

JavaScript Validation

As I'm mainly a php developer I am used to using the function is_numeric. But when doing client-side validation on forms, JavaScript doesn't have a is_numeric function the best it can do is isNan, which doesn't do enough to get what I want from my validation. Therefore I was out on the hunt for a function in JavaScript which can help.

There wasn't any raw Javascript functions which did what I needed so it was clear that I needed to create my own function to do the job. After a few searches on some forums and blogs I found a solution which should do exactly what I need from a is_numeric function.

This will check if the input is a number and it doesn't matter if it is a decimal number or a negative number this function will return true.

JavaScript Is Number Function

function IsNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}

Subscribe To Newsletter

Get weekly updates to your email