Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To allow only numbers and dot, use this regex /^[0-9]*\.?[0-9]*$/ it will return true if value contain only numbers and dots.

Let’s see short example of javascript regex allow numbers and decimals only.

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

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 allow only numbers and dot in javascript using regex?

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

Javascript regex allow only numbers and dot example

Here, we will create common validate function where we will validate param should numbers and dots.

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

// validate integer
console.log(validate(39))

// validate float
console.log(validate(39.89))

// validate string float
console.log(validate("39.89"))

// validate string float with e
console.log(validate("39.89e"))

// validate char string
console.log(validate("one"))

// validate Boolean
console.log(validate(true))

Output

Typescript regex allow only numbers and dot example

Same like javascript, we will create a function and call it with diffrent parameters.

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

// validate integer
console.log(validate(39))

// validate float
console.log(validate(39.89))

Output

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