PHP - 如果选择了选项,则选择Multiselect require字段

时间:2013-01-14 17:12:03

标签: php multi-select required

这是通过电子邮件发送的表单的一部分。当您选择选项状态时,文本字段状态是必需的,如果不是,则不是,县和邮政编码相同。 我想要的是php验证这个,所以我可以发送电子邮件,但到目前为止我还没有完成它。

这是HTML:

<select multiple="multiple" name="geographic" id="geographic">
    <option value="state">State</option>
    <option value="county">County</option>
    <option value="zip">Zip Code</option>
</select>
<label for="state">What state?</label>
<input id="state" name="state" type="text">
<label for="county">What County?</label>
<input id="county" name="county" type="text">
<label for="zipcode">What is the Zip Code? *</label>
<input id="zipcode" name="zipcode" type="text">

2 个答案:

答案 0 :(得分:1)

您可以使用Javascript允许在前端进行验证,而不需要页面加载,以下内容应该对您有用:

<head>
<script type="text/javascript">
function SelectValidator() {
  // Get the select object
  var index = document.getElementById("geographic").selectedIndex;
  var select = document.getElementById("geographic").options;

  // Get our input elements
  var county = document.getElementById('county');
  var state = document.getElementById('state');
  var zipcode = document.getElementById('zipcode');

  if (select[index].value === "county") {
    if (county.value === null || county.value === "") {
      alert("Please complete the County field");
    } else {
      alert("You could simply put a return statement here.");
    }
  } else if (select[index].value === "state") {
    if (state.value === null || state.value === "") {
      alert("Please complete the state field");
    } else {
      alert("You could simply put a return statement here.");
    }
  } else if (select[index].value === "zip") {
    if (zipcode.value === null || zipcode.value === "") {
      alert("Please complete the Zip Code field");
    } else {
      alert("You could simply put a return statement here.");
    }
  }
}
</script>
</head>

你的表格:

<form>
<select multiple="multiple" name="geographic" id="geographic">
    <option value="state">State</option>
    <option value="county">County</option>
    <option value="zip">Zip Code</option>
</select>

<label for="state">What state?</label>
<input id="state" name="state" type="text">

<label for="county">What County?</label>
<input id="county" name="county" type="text">

<label for="zipcode">What is the Zip Code? *</label>
<input id="zipcode" name="zipcode" type="text">


<button type="button" onclick="SelectValidator()">Display index</button>
</form>

答案 1 :(得分:-1)

首先你需要将代码包装在一个表单中,但你可能已经这样做了吗?如果没有,你应该看看http://www.w3schools.com/php/php_forms.asp

发布表单的php文件用$ _POST接收它,在geopit的情况下是$ _POST ['geographic'],同样适用于状态。现在您知道如何访问该值,您可以对其进行验证。

所以

if($_POST['geographic'] == 'state'){

     if(empty($_POST['state'])){
          echo 'state is required';
     }else{
          echo 'state is given, proceed';
     }

}