user6791369 user6791369 - 2 months ago 13
Javascript Question

Check if prompt only contains numbers and commas

I have a prompt in JS:

var ask = prompt("What content do you want to link?");


I only want
ask
to contain numbers and commas. For example, an example input might be:
5,3,1


I know you can't do this during the prompt, but I want to validate the information after the prompt. So:

if(ask only contains numbers and commas) {
alert("True!");
}

Answer

You can try use regex like below, which matches a number or numbers separated by commas

var ask = prompt("What content do you want to link?");
if (ask) {
  if (ask.match(/^[0-9]+[(,)(0-9)]*[0-9]+$/))
    alert("correct format")
  else
    alert("wrong format")
}

Comments