如何验证支票按钮&单选按钮

时间:2013-01-14 13:03:05

标签: php validation checkbox radio-button

我已经准备好了验证号码,电子邮件和消息等等。

我现在的问题是如何验证radio / check btn。

以下是我如何验证等消息:

// Validates msg

if (!isset($_POST[$field]) || empty($_POST['message'])) {
    $error_msg .= " ";  
    $fieldStatusMessage = 'style="border:1px solid #F00"';
}
else {
    $fieldStatusEmail = '';
}

如果有人可以解释或告诉我,会有所帮助。我认为它非常接近我现在正在做的事情?

3 个答案:

答案 0 :(得分:1)

您可以执行以下操作

示例1

PHP

<?php
  if($_Post[]) {
        if($_POST['list'] == -1)
                echo 'Please select one on the List';
         else {
                ............
         }
}
?>

HTML

<form method="post">
 <select name="list">
         <option value="-1">Select One</option>
         <option value="1">One</option>
         <option value="2">Two</option>
</select>
<input type="submit" name="submit">
</form>

示例2

HTML

<form name="frm1" action="action.php" method="post">
    Active ? 
    <input type="radio" name="myrdo" value="Y" /> Yes
    <input type="radio" name="myrdo" value="N" /> No
    <br />
    Education:
    <input type="checkbox" name="mychk" value="G" /> Graduate
    <br />
    Country:
    <select name="country">
        <option value="" selected="selected">Select</option>
        <option value="1">USA</option>
        <option value="2">UK</option>
        <option value="3">Canada</option>
    </select>
    <br />
    <input type="submit" name="btnSubmit" value="Submit Form" />
</form>

PHP

if($_SERVER['REQUEST_METHOD'] == 'POST'){ 
    $error_msg = array(); 
    if(!isset($_POST['myrdo'])){ 
        $error_msg[] = "No radio buttons were checked."; 
    } 
    if(!isset($_POST['mychk'])){ 
        $error_msg[] = "Graguate was checked"; 
    } 
    if(!isset($_POST['country'])){ 
        $error_msg[] = "No country as selected."; 
    } 

    if(isset($error_msg) && count($error_msg) == 0){ 
        // do some form processing 
    } 
    else{ 
        // redirect to the form again. 
    } 
}  

Read more

答案 1 :(得分:1)

如果用户选中了复选框,则$ _POST ['checkboxName']等于“on”。如果用户取消选中它,$ _POST ['checkboxName']将不存在。

对于一个单选按钮,你的$ _POST ['radioName']等于所选的值(html attribut value)

答案 2 :(得分:0)

// if not checked consider FALSE
$checkbox = (empty($_POST['checkbox_name'])) ? FALSE : TRUE;

// if not selected consider FALSE otherwise use value from HTML.
$radio = (empty($_POST['radio_name'])) ? FALSE : $_POST['radio_name'];