简体   繁体   中英

How can you use form validation to go through multiple options?

The rest of the form validation worked fine, until I got to this: Sex must be a single character equal to M, m, F, or f

<script>
    function verify() {
        if (document.forms[0].age.value < 18) {
            alert ("Age must be between 18 and 30");
            return false;
        } 
        if (document.forms[0].age.value > 30) {
            alert ("Age must be between 18 and 30");
            return false;
        } 
        if (document.forms[0].age.value == "") {
            alert ("Age must be between 18 and 30");
            return false;
        } 
        if (document.forms[0].last.value == "") {
            alert ("Last name canot be empty.");
            return false;
        } 
        if (document.forms[0].sex.value !== "M" || "m" ||"F" ||"f")
            alert ("Please indicate your sex.");
            return false;
        } 
        alert ("Thank you for your submission.")
            return true;
    }
</script>

Expected: Pop ups for each issue with the form submission. I got a few before adding the bit about the sex validation.

Actual: Now no pop ups are occurring.

Your validation for sex is incorrect. When doing a boolean or (||) the condition must appear on all sides of the ||.

To fix this, change your code for sex validation to:

 var sex = document.forms[0].sex.value;
 if ( sex !== "M" || sex !== "m" || sex !== "F" || sex !== "f") {
     alert ("Please indicate your sex.");
     return false;
 } 

As you can see, the if statement checks the sex against each value respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM