0

I need help with rejecting an invalid string in JS:

I want to ensure any input other than the numbers 1-6 is rejected e.g 0 or 7+ or any other character, here is what i got so far

function getGraph() {
  var i;
  var results = [];
  var dicePoss = [1, 2, 3, 4, 5, 6]
  var tracker;

  for (i = 1; i <= 30; i++) {
    tracker = parseInt(results.push(prompt("Enter your numbers", 'diceroll')));

  }

  if (tracker <= 6 && tracker > 0) {
    document.getElementById('x-axis').innerHTML = tracker;
  } else {
    document.getElementById('reject').innerHTML = "Please enter a numberPlease enter a valid number between 1-6";
  }

  document.getElementById('y-axis').innerHTML = dicePoss;
}
<!DOCTYPE html>

<html>

<body>

  <p id="y-axis">Frequency of die rolls(results)</p>
  <p id="x-axis">Dice Possible Rolls between 1-6</p>
  <p id="reject"></p>

  <input type="button" value="Graph Column Chat for Dice Roll" onclick="getGraph();">
</body>

</html>

1

1 Answer 1

2

To fix the issue you can use regular expressions:

var str = prompt("Enter your numbers",'diceroll');

if (str.match(/^[1-6]$/)) {
   results.push(str);
} else {
   // show error
}

And some comment about your code, you have this:

for (i = 1; i <= 30; i++) {
    tracker = parseInt(results.push(prompt("Enter your numbers", 'diceroll')));

}

which is wrong in two ways:

  • first it will parse result of push which is index (number) of last pushed value.
  • and second is that the value will be last push (tracker === 30).

In my code the check goes inside the loop, not outside of it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.