Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To accept only numbers, use this regex ^[0-9]*$ it will return true if value contain only numbers.

Let’s see short example to use regex in javascript

const regex = /^[0-9]*$/;
console.log(regex.test(90))

Today, I’m going to show you How do I check value contain only numbers and dot in javascript, as above mentioned, I’m going to use the above-mentioned regex with test() method.

Let’s start today’s tutorial how do you accept only numbers in javascript using regex?

Here, I will show accept only numbers in javascript and typescript.

Javascript regex accept only numbers example

Here, we will create common validate function where we will validate param should contain only numbers.

function validate(param){
  const regex = /^[0-9]*$/;
  return regex.test(param);
}

// validate empty
console.log(validate(""))
// false

// validate number
console.log(validate(39))
// true

// validate zero
console.log(validate(0))
// true

// validate nan
console.log(validate(NaN))
// false

Output

Typescript regex accept only numbers example

Here, we will create common validate function where we will validate param should contain only numbers.

function validate(param: number){
  const regex = /^[0-9]*$/;
  return regex.test(param.toString());
}


// validate number
console.log(validate(39))
// true

// validate zero
console.log(validate(0))
// true

// validate nan
console.log(validate(NaN))
// false

Output

I hope it helps you, All the best đź‘Ť.