[javascript] (Built-in) way in JavaScript to check if a string is a valid number

If you're just trying to check if a string is a whole number (no decimal places), regex is a good way to go. Other methods such as isNaN are too complicated for something so simple.

    function isNumeric(value) {
        return /^-?\d+$/.test(value);
    }
    
    console.log(isNumeric('abcd'));         // false
    console.log(isNumeric('123a'));         // false
    console.log(isNumeric('1'));            // true
    console.log(isNumeric('1234567890'));   // true
    console.log(isNumeric('-23'));          // true
    console.log(isNumeric(1234));           // true
    console.log(isNumeric('123.4'));        // false
    console.log(isNumeric(''));             // false
    console.log(isNumeric(undefined));      // false
    console.log(isNumeric(null));           // false

To only allow positive whole numbers use this:

    function isNumeric(value) {
        return /^\d+$/.test(value);
    }

    console.log(isNumeric('123'));          // true
    console.log(isNumeric('-23'));          // false

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to numeric

How to convert entire dataframe to numeric while preserving decimals? What's the difference between integer class and numeric class in R IsNumeric function in c# How to compare numbers in bash? Right way to convert data.frame to a numeric matrix, when df also contains strings? angularjs: allows only numbers to be typed into a text box How to convert Varchar to Double in sql? SQL Server : error converting data type varchar to numeric How do I convert certain columns of a data frame to become factors? How to create a numeric vector of zero length in R