2017-12-27 146 views
-2

我有一个包含无线电输入的表单。无线电输入可以是0,1或选择enot。我正在尝试进行输入验证,以确保值在发布到数据库之前仅为0,1或空。不知怎的,下面的代码不起作用。空无线电输入验证

有人可以帮我吗?

$posttodatabase = true; 
$array = (0, 1); 
if (!in_array($_POST['x'], $array) && isset($_POST['x'])) { 
    $posttodatabase = false; 
}; 

编辑:所附表格:

 <form action='registration.php' method=POST> 
      <input type="radio" name="x" value=0> Foo 
      <input type="radio" name="x" value=1> Bar 
      <input class="button" type=submit value='Submit'> 
     </form> 
+0

更新您的问题,包括在HTML /形式。 –

+0

你应该在表格中引用所有内容,这可能会对你有所帮助。无论哪种情况,下面都有几个答案。 –

回答

1

不要设置$posttodatabase默认true并将其更改为false时,不符合要求。当需求满足(值存在且是预期值之一)时,反过来使用它来确保只将值设置为true

$posttodatabase = false; 
if (!isset($_POST['x']) OR     // is not set OR 
    (
     isset($_POST['x']) AND    // is set and... 
     in_array($_POST['x'], array(0, 1)) // ... one of these values 
    )) { 
    $posttodatabase = true; 
} 

(或直接赋值...)

+0

不幸的是,这并没有捕获空的无线电值(当未指定任何选项时发生)。我该如何解决这个问题? – StudentAsker

+0

@StudentAsker没有选择是一个有效的选项/“输入”? – Progman

+0

这是正确的。 – StudentAsker