0

My question is about validating form data with JavaScript. I have a bunch of validation code that works great because it returns false. I am, however, trying to validate my form using a switch statement, but am struggling because it returns true:

switch (course) {
  case "CIS 100":
    if (section == '100001')
      return true;
    if (section == '100gw1')
      return true;
    else
      window.alert("You must select a valid section for CIS 100!");
    return false;
    break;

Once the function returns true, the rest of my code executes and doesn't run through the rest of my validation. I thought that the break statement would prevent this, but it didn't. Is a switch statement the wrong way to go? Is there a way to do the switch statement without doing the "return true"? Advice is appreciated. If you need to see more of my code, let me know. I didn't want people to think I was asking them to do my assignment for me.

Complete Code as requested:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!--Document Head-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!--Title Element-->
<title>Greendale Community College</title>
<!--Style Element-->
<style type="text/css">
    body {
        background-color: white;
    }

    h1 {
        text-align: center;
        font-family: Impact;
        color: green;
    }

    p {
        font-size: 72px;
        color: green;
    }
</style>
<!--Script Element-->
<script type="text/javascript">
    /* <![CDATA[ */
    // function to validate and create message confirm box
    function submitRegistration() {
        var fName = document.registration.firstName.value;
        var lName = document.registration.lastName.value;
        var cwid = document.registration.cwid.value;
        var semester = document.registration.semester.value;
        var course = document.registration.courses.value;
        var section = document.registration.section.value;
        var major = document.registration.needForMajor.value;
        var semesterDisplay;
        // To display semester info in confirm message
        if (semester == "fall")
            semesterDisplay = "Fall";
        if (semester == "spring")
            semesterDisplay = "Spring";
        if (semester == "summer")
            semesterDisplay = "Summer";
        //To display major requirement in confirm message
        var checkDisplay;
        if (document.registration.needForMajor.checked == true) {
            checkDisplay = "Course Needed For Major";
        }
        else {
            checkDisplay = "";
        }
        //Validates first name
        if (fName == "") {
            window.alert("You must enter your first name!");
            return false;
        }
        //Validates that first name is non-numeric
        if (isNaN(fName) == false) {
            window.alert("Your First Name must be non-numeric values!");
            return false;
        }
        //Validates last name
        if (lName == "") {
            window.alert("You must enter your last name!");
            return false;
        }
        //Validates that last name is non-numeric
        if (isNaN(lName) == false) {
            window.alert("Your Last Name must be non-numeric values!");
            return false;
        }
        //Validates CWID
        if (cwid == "") {
            window.alert("You must enter your cwid!");
            return false;
        }
        //Validates that CWID is numeric
        if (isNaN(cwid) == true) {
            window.alert("Your CWID must be numeric values!");
            return false;
        }
        //Validates semester
        var validateSemester = false;
        for (var i = 0; i < 3; ++i) {
            if (document.registration.semester[i].checked == true) {
                validateSemester = true;
                break;
            }
        }
        if (validateSemester != true) {
            window.alert("You must select a Semester!");
            return false;
        }
        //Validates course
        if (course == "") {
            window.alert("You must select a Course!");
            return false;
        }
        switch (course) {
            case "CIS 100":
                if (section == '100001')
                    return true;
                if (section == '100gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 100!");
                return false;
                break;
            case "CIS 120":
                if (section == '120001')
                    return true;
                if (section == '120gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 120!");
                return false;
                break;
            case "CIS 220":
                if (section == '220001')
                    return true;
                if (section == '220gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 220!");
                return false;
                break;
            case "CIS 299":
                if (section == '299001')
                    return true;
                if (section == '299gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 299!");
                return false;
                break;
            case "CIS 302":
                if (section == '302gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 302!");
                return false;
                break;
            case "CIS 304":
                if (section == '304001')
                    return true;
                if (section == '304gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 304!");
                return false;
                break;
            case "CIS 321":
                if (section == '321001')
                    return true;
                if (section == '321gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 321!");
                return false;
                break; 
            case "CIS 322":
                if (section == '322gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 322!");
                return false;
                break;
            case "CIS 325":
                if (section == '325gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 325!");
                return false;
                break;
            case "CIS 330":
                if (section == '330001')
                    return true;
                if (section == '330gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 330!");
                return false;
                break;
            case "CIS 332":
                if (section == '332001')
                    return true;
                if (section == '332gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 332!");
                return false;
                break;
            case "CIS 341":
                if (section == '341001')
                    return true;
                if (section == '341gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 341!");
                return false;
                break;
            case "CIS 343":
                if (section == '34301a')
                    return true;
                if (section == '34301b')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 343!");
                return false;
                break;
            case "CIS 352":
                if (section == '352gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 352!");
                return false;
                break;
            case "CIS 354":
                if (section == '354001')
                    return true;
                if (section == '354gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 354!");
                return false;
                break;
            case "CIS 401":
                if (section == '401gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 401!");
                return false;
                break;
            case "CIS 419":
                if (section == '419x01')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 419!");
                return false;
                break;
            case "CIS 490":
                if (section == '490001')
                    return true;
                if (section == '490gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 490!");
                return false;
                break;
            case "CIS 492":
                if (section == '492gw1')
                    return true;
                else
                    window.alert("You must select a valid section for CIS 492!");
                return false;
                break;
            case "MAT 195":
                if (section == '195001')
                    return true;
                if (section == '195w01')
                    return true;
                else
                    window.alert("You must select a valid section for MAT 195!");
                return false;
                break;
            case "MAT 215":
                if (section == '215001')
                    return true;
                if (section == '215w01')
                    return true;
                else
                    window.alert("You must select a valid section for MAT 215!");
                return false;
                break;
            case "MAT 225":
                if (section == '225001')
                    return true;
                if (section == '225w01')
                    return true;
                else
                    window.alert("You must select a valid section for MAT 225!");
                return false;
                break;
            case "MAT 281":
                if (section == '281001')
                    return true;
                if (section == '281w01')
                    return true;
                else
                    window.alert("You must select a valid section for MAT 281!");
                return false;
                break;
        }
        //Validates section
        if (section == "") {
            window.alert("You must select a Section!");
            return false;
        }  
        //Confirm message
        var confirmation = window.confirm("Student Name: " + fName + " " + lName + "   CWID: " + cwid + "   Semester: " + semesterDisplay + "   Course: " + course + "   Section: " + section + "   " + checkDisplay);
        //Ok and Cancel buttons
        if (confirmation) {
            window.alert("You have been registered for your course!");
        }
        else {
            window.alert("Your registration has been canceled.");
        }
    }
    //Reset function
    function resetRegistration() {
        var resetForm = window.confirm("Are you sure you want to reset the form?");
        if (resetForm == true)
            return true;
        return false;
    }
    //Functions for mouseover and mouseout
    function mouseOver(target) {
        target.src = 'greendale_paper.png'
        target.alt = 'paper'
    }

    function mouseOut(target) {
        target.src = 'greendale.jpg'
        target.alt = 'greendale'
    }
    /* ]]> */
</script>
</head>
<body>
<!--Heading Element-->
    <h1>Greendale Community College</h1>
        <!--Added a mouseover and mouseout-->
        <center><img src="greendale.jpg" alt="greendale"  width="560" height="315" 
            onmouseover="mouseOver(this)"
            onmouseout="mouseOut(this)" 
        /></center>
    <h3 align="center">Greendale Community College Orientation Video</h3>
    <center><iframe width="560" height="315" src="https://www.youtube.com/embed/i3z5QO2O3cU" frameborder="0" allowfullscreen=allowfullscreen></iframe></center>
    <h2 align="center">Course Registration Page</h2>
<form action="FormProcessor.html" name="registration" method="get"
      onsubmit="return submitRegistration()"
      onreset="return resetRegistration()">
    <h3>Student Information Form</h3> 
    <!--Student Information-->
    First Name:<input type="text" name="firstName"/><br />
    Last Name:<input type="text" name="lastName"/><br />
    CWID:<input type="text" name="cwid" size="8" /><br />
    <h3>Semester</h3>
    <h4>(choose a semester)</h4>
    <!--Radio Buttons to Choose Semester-->
    <input type="radio" name="semester" value="fall" /> Fall 2018 <br />
    <input type="radio" name="semester" value="spring" /> Spring 2018 <br />
    <input type="radio" name="semester" value="summer" /> Summer 2018 <br />
    <h3>Courses</h3>
    <h4>(choose one course)</h4>
    <table>
        <!--Drop Down Box for Courses-->
        <tr><td style="background:white;border:0">Courses:</td>
            <td>
                <select name="courses" size="1">
                    <option value=""></option>
                    <option value="CIS 100">CIS 100 Intro to CIS</option>
                    <option value="CIS 120">CIS 120 Application Prog I</option>
                    <option value="CIS 220">CIS 220 Application Prog II</option>
                    <option value="CIS 299">CIS 299 System Analysis I</option>
                    <option value="CIS 302">CIS 302 Visual Programming</option>
                    <option value="CIS 304">CIS 304 Cobol</option>
                    <option value="CIS 321">CIS 321 DB Mgt Sys and Design</option>
                    <option value="CIS 322">CIS 322 DB App Development</option>
                    <option value="CIS 325">CIS 225 Dec Support Systems</option>
                    <option value="CIS 330">CIS 330 Web Programming I</option>
                    <option value="CIS 332">CIS 332 Web Programming II</option>
                    <option value="CIS 341">CIS 341 CISCO CCNA I</option>
                    <option value="CIS 343">CIS 343 CISCO CCNA III</option>
                    <option value="CIS 352">CIS 352 Global Ethics in Comp</option>
                    <option value="CIS 354">CIS 354 Sys Project Mgt</option>
                    <option value="CIS 401">CIS 401 Concepts Enter Res Planning</option>
                    <option value="CIS 419">CIS 419 CIS Internship</option>
                    <option value="CIS 490">CIS 490 Systems Analysis II</option>
                    <option value="CIS 492">CIS 492 Systems Dev and Imp</option>
                    <option value="MAT 195">MAT 195 Discrete Math Structures</option>
                    <option value="MAT 215">MAT 215 Statistics</option>
                    <option value="MAT 225">MAT 225 Business Statistics</option>
                    <option value="MAT 281">MAT 281 Calculus I</option>
                </select>
            </td>
        </tr>
    </table>
    <h3>Sections</h3>
    <h4>(choose one section)</h4>
    <table>
        <tr><td style="background:white;border:0">Section Numbers:</td>
            <td>
                <!--Selection Box-->
                <select name="section" multiple="multiple" size="5">
                    <option value="100001">CIS 100 001</option>
                    <option value="100gw1">CIS 100 GW1</option>
                    <option value="120001">CIS 120 001</option>
                    <option value="120gw1">CIS 120 GW1</option>
                    <option value="220001">CIS 220 001</option>
                    <option value="220gw1">CIS 220 GW1</option>
                    <option value="299001">CIS 299 001</option>
                    <option value="299gw1">CIS 299 GW1</option>
                    <option value="302gw1">CIS 302 GW1</option>
                    <option value="304001">CIS 304 001</option>
                    <option value="304gw1">CIS 304 GW1</option>
                    <option value="321001">CIS 321 001</option>
                    <option value="321gw1">CIS 321 GW1</option>
                    <option value="322gw1">CIS 322 GW1</option>
                    <option value="325gw1">CIS 325 GW1</option>
                    <option value="330001">CIS 330 001</option>
                    <option value="330gw1">CIS 330 GW1</option>
                    <option value="332001">CIS 332 001</option>
                    <option value="332gw1">CIS 332 GW1</option>
                    <option value="341001">CIS 341 001</option>
                    <option value="341gw1">CIS 341 GW1</option>
                    <option value="34301a">CIS 343 01A</option>
                    <option value="34301b">CIS 343 01B</option>
                    <option value="352gw1">CIS 352 GW1</option>
                    <option value="354001">CIS 354 001</option>
                    <option value="354gw1">CIS 354 GW1</option>
                    <option value="401gw1">CIS 401 GW1</option>
                    <option value="419x01">CIS 419 X01</option>
                    <option value="490001">CIS 490 001</option>
                    <option value="490gw1">CIS 490 GW1</option>
                    <option value="492gw1">CIS 492 GW1</option>
                    <option value="195001">MAT 195 001</option>
                    <option value="195w01">MAT 195 W01</option>
                    <option value="215001">MAT 215 001</option>
                    <option value="215w01">MAT 215 W01</option>
                    <option value="225001">MAT 225 001</option>
                    <option value="225w01">MAT 225 W01</option>
                    <option value="281001">MAT 281 001</option>
                    <option value="281w01">MAT 281 W01</option>
                </select>
                </td>
            </tr>
    </table>
    <!--Checkbox-->
    <input type="checkbox" name="needForMajor" />
    Check if the course is required for your major!<br />
    <!--Submit and Reset Buttons Created-->
    <input type="submit" name="submit" value="Submit"/><br />
    <input type="reset" name="reset" value="Reset"/>
    </form>
    </body>
</html>
2
  • Please update your posted code to 1) correct for the fact that you are not showing the complete code for your switch, 2) show the function that the switch is in and 3) all the relevant HTML and CSS. Commented Jul 27, 2017 at 15:43
  • Calling return will exit the function, right then and there. What break does is prevent other switch cases from being tested. Commented Jul 27, 2017 at 15:49

4 Answers 4

1

You shouldn't be using return here at all. All you need to do is set a "flag" that validation has failed and then check the flag.

Additionally, when it comes to validation, you only need to test for invalid data and only stop the submission when you have that. If the data is good, don't do anything and just let the process happen as normal.

Here's an example of how a form submit event handler might look:

formReference.addEventListener("submit", function(evt){
  var valid = true;
  var message = "";

  // Switch is best when there is a single value that you want to look at
  // if is best when there are different tests to perform

  // If course is good, but section is bad...
  if (course === "CIS 100" && (section !== '100001' && section !== '100gw1')){
    message = "You must select a valid section for CIS 100!";
    valid = false;
  } else if(// Next test for invalid value here) {
    message = "next message";
    valid = false;
  } 

  // After doing the tests, just check the flag
  if(!valid){
    // Error! Show message
    alert(message);

    // Cancel the form submission
    evt.preventDefault();
    evt.stopPropagation();
  }
});
Sign up to request clarification or add additional context in comments.

2 Comments

section !== '100001' || section !== '100gw1' will always evaluate to true; you need && ;)
Thanks....I syphoning through the suggestions and working on it. I'm really new to this (web programming I) and am trying to ask relevant pointed questions. Your help is truly appreciated.
0

You can try this way, I've added some code with assumption. Here the return state causing you the main problem. It prevents to execute the break statement.

var wrong;
switch (course) {
  case "CIS 100":
    if (section == '100001')
      wrong = false;
    else if (section == '100gw1')
      wrong = false;
    else
      window.alert("You must select a valid section for CIS 100!");
      wrong = true ;
  break;

 case "CIS 200":
    if (section == '200002')
      wrong = false;
    else if (section == '100gw1')
      wrong = false;
    else
      window.alert("You must select a valid section for CIS 100!");
      wrong = false ;
 default:
      wrong = true ;
}

return wrong ;

Comments

0

You can use your method without an additional variable, like this:

function validate() {
  switch (course) {
    case "CIS 100":
      switch (section) {
        case '100001':
        case '100gw1':
          break;
        default:
          alert("You must select a valid section for CIS 100!");
          return false;
      }
      break;
    case "CIS 200":
      switch (section) {
        case '200001':
        case '200gw1':
          break;
        default:
          alert("You must select a valid section for CIS 200!");
          return false;
      }
      break;
  }
  // rest of validation
  return true;
}

8 Comments

On a related note; if those are <select> options, you might want to populate the section option based on the course option.
This may work, but it is not a good solution at all (nested switchs, multiple alerts, irrelevant returns).
@ScottMarcus I'm always open to constructive criticism; is this about returning out of a case? Or about something else?
From the OP " Is a switch statement the wrong way to go?" Yes, it is. It requires the convoluted answer that you've posted.
I agree that my solution is far from the ideal one, I personally would solve this entire thing in a radically different way. I just wanted to point out where the OP's specific error was by providing a minimally edited working version. Your critique of my answer is mostly about stylistic choices, and I basically agree with them.
|
0

I thought that the break statement would prevent this, but it didn't.

The break statement is never reached. The return statement causes the function to return immediately.

It sounds like you are trying to test multiple things and return false if any of them fail.

So create a variable which defaults to being true.

var nothing_is_wrong = true;

Then during your tests:

  • If a test is OK, do nothing
  • If a test is not OK, set that variable to false

such:

switch (course) {
  case "CIS 100":
    if (section == '100001') {
      // It's fine! Do nothing
    } else if (section == '100gw1') {
      // It's fine! Do nothing
    } else {
      window.alert("You must select a valid section for CIS 100!");
      // It's not fine! :(
      nothing_is_wrong = false;
    }
  break;

Then, finally, return that variable

return nothing_is_wrong;

2 Comments

Yeah, but if you aren't going to do anything in the first two if branches, don't test for them. Combine their opposite tests into a single test and set the false flag if the invalid test is true.
Also, in your else, you should have nothing_is_wrong = false since that's the section where it's determined that something is wrong.

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.