如何正确验证复选框值

how to properly validate a checkbox values

本文关键字:复选框 验证 何正确      更新时间:2023-09-26

我正在尝试将checkbox值上传到我的db,它正在正确上传,但没有得到验证。如果我没有选中任何内容,它仍然POST其他字段上的其余值,而不是提醒我从复选框中进行选择。我的所有设置都无法正常工作。我是否正确验证了checkbox值?

这是我的HTML代码:

<table width="200">
    <tr>
        <td>
            <label>
                <input type="checkbox" name="Verification[]" value="Test1" id="Verification_0" />
                BuildServerPath</label>
        </td>
    </tr>
    <tr>
        <td>
            <label>
                <input type="checkbox" name="Verification[]" value="Test2" id="Verification_1" />
                File Exist</label>
        </td>
    </tr>
    <tr>
        <td>
            <label>
                <input type="checkbox" name="Verification[]" value="Test3" id="Verification_2" />
                WBS Code</label>
        </td>
    </tr>
    <tr>
        <td>
            <label>
                <input type="checkbox" name="Verification[]" value="Test4" id="Verification_3" />
                UAT Contact</label>
        </td>
    </tr>
</table>

这是我POST的方式,我有两个选择

$Verification = implode(''r', $_POST['Verification']);

$verify=""; 
$flag=0; 
foreach($Verification as $entry){ 
    $verify .= $entry."'r"; 
    $flag=1; 
} 
if($flag==1){ 
    $verify=rtrim($verify); 
} 

现在,这是我尝试验证它的方式。这种类型的验证适用于我的radio buttontext fields; document.form1.verify.value==""更改为verifyVerification,具体取决于我使用的发布方法

function validateDBLoad()
{
    if ((document.form1.verify.value == "")
    {
        alert('Please fill up all the fields..');
        return false;
    }
    else
    {
        alert('Ticket upload Successful.');
        return true;
    }
} 

我还尝试按照这里的步骤操作: 复选框验证器,但似乎不适用于我已经设置的验证代码,它给了我"请选择一个复选框!"的警报,但同时上传了我的其他值,

这是我尝试过的js

var inputs = document.getElementById('my-form').getElementsByTagName('input');
var checked = 0;
for (var i = 0, length = inputs.length; i < length; i++) {
    if (inputs[i].getAttribute('type') !== 'checkbox') {
       continue;
    }
    if (inputs[i].checked) {
        checked++;
    }
}
if (checked === 0) {
   alert('Select a checkbox, please!');
}
简单地说,

你可以这样做

if(document.querySelectorAll('#my-form input[type=checkbox]:checked').length===0){
   alert("Please select atleast one checkbox");
   return false;
}
if(validationForYourOtherFieldsIsNotFine){
   alert("Other validations will happen here");
   return false;
}