Home > Enterprise >  How can I create a Regex that only lets in comma separated numbers?
How can I create a Regex that only lets in comma separated numbers?

Time:09-04

I want my user to be able to add multiple numeric values separated by commas. For example,

Allowed Strings

1,2,3
.1,2.0,3.,

Not Allowed

1,,2..3
1,2,.,3,.

I have this so far:

/(\.?)(\d )(,?)/g

As a bonus, I would also like to have the regex that I could give to the JS match method which will give me an array of the values entered by the user.

CodePudding user response:

You can use a function that will split the string by the comas and then check if every items are numbers (!isNaN) to decide to return the splitted string (an array) or something else.

const allowed_1 = "1,2,3"
const allowed_2 = ".1,2.0,3.,"

const notAllowed_1 = "1,,2..3"
const notAllowed_2 = "1,2,.,3,."

const checkNumbers = (string) => {
  items = string.split(",")
  return items.every((item) => !isNaN(item)) ? items : "Not allowed"
}

console.log(checkNumbers(allowed_1))
console.log(checkNumbers(allowed_2))

console.log(checkNumbers(notAllowed_1))
console.log(checkNumbers(notAllowed_2))

CodePudding user response:

^(((\d*\.?\d )|(\d \.?\d*))(,)|((\d*\.?\d )|(\d \.?\d*))) $

edit: thanks to @Brooke because my 1st answer had an error, now this one should work perfect

  • Related