PHP validation checkbox

前端 未结 3 1194
野性不改
野性不改 2021-01-29 03:06

I\'ve scoured the entire internet trying to find a solution to what I\'m missing here (or doing wrong). My form doesn\'t validate even when the check box is checked. Everything

相关标签:
3条回答
  • 2021-01-29 03:23

    The problem with your current validation is that you're using if-else wrongly and that you're using exit on every statement which will terminate your script prematurely.

    You can do this instead:

    For Terms:
    <input type="checkbox" class="form-check-input" name="terms" id="terms" value="1"/>    
    
    //set an error counter to trigger the `exit`
    $error_counter = 0;
    if(trim($name) == '') {
        echo '<div class="error_message">Attention! You must enter your name</div>';
        $error_counter++;
    } 
    if(trim($email) == '') {
        echo '<div class="error_message">Attention! Please enter a valid email 
    address.</div>';
        $error_counter++;
    }
    if(!isEmail($email)) {
        echo '<div class="error_message">Attention! You have entered an invalid e- 
    mail address, try again.</div>';
        $error_counter++;
    } 
    if(trim($subject) == '') {
        echo '<div class="error_message">Attention! Please enter a subject.</div>';
        $error_counter++;
    }
    if(trim($comments) == '') {
        echo '<div class="error_message">Attention! Please enter your message.</div>';
        $error_counter++;
    }
    if(empty($terms)) {
        echo '<div class="error_message">Attention! Please agree to our terms of service.</div>';
        $error_counter++;
    }
    //if `$error_counter > 0 > 0` it will trigger the `exit()` to stop the script and display the errors.
    if($error_counter > 0){
        exit();
    }
    

    There's a more beautiful approach to do this. Feel free to add suggestions for the OP.

    0 讨论(0)
  • 2021-01-29 03:37

    You don't set any value attribute for your checkbox :

    <input type="checkbox" class="form-check-input" name="terms" id="terms" value="yes" />
    

    More informations : https://developer.mozilla.org/fr/docs/Web/HTML/Element/Input/checkbox

    0 讨论(0)
  • 2021-01-29 03:37

    I can see your checkbox has no value so the PHP part is getting a garbage/empty value.

    In short, just add a required attribute in your HTML side. No need of a check at the server end

    <div class="form-check">
          <input type="checkbox" class="form-check-input" name="terms" id="terms" required/>
         <label class="form-check-label" for="terms"><p>I agree to terms of service.</p></label>
    </div>
    
    0 讨论(0)
提交回复
热议问题