0

I'm attempting an exercise and can't quite understand where I'm going wrong.

I have a form where my postcode field will only validate if it meets the requirements of the regex specific to the state chosen. I need to use a switch statement to determine what RegEx to use based on the state choice.

This is what I have so far:

function validPostCode() {
  var state = (document.getElementById("state").value);

  switch (state) {
    case "SA":
    var stateRegEx = /^5([0-9]{3})$/;
    break;
    case "NSW":
    var stateRegEx = /^2([0-9]{3})$/;
    break;
  }
  return stateRegEx.test(document.getElementById("postcode").value);
}
1
  • What's your question? Is the code breaking? Commented Sep 15, 2014 at 12:11

1 Answer 1

1

Try this:

function validPostCode() {
  var state = (document.getElementById("state").value);
  var stateRegEx;            // added here

  switch (state) {
    case "SA":
    stateRegEx = /^5([0-9]{3})$/;    // var removed
    break;
    case "NSW":
    stateRegEx = /^2([0-9]{3})$/;    // var removed
    break;
  }
  return stateRegEx.test(document.getElementById("postcode").value);
}
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.