-5

这是通过电子邮件发送的表格的一部分。当您选择选项状态时,文本字段状态是必需的,如果您不这样做,则县和邮政编码相同。我想要的是 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">
4

2 回答 2

1

您可以使用Javascriptwhich 允许在前端进行验证并且不需要页面加载,如下所示应该适合您:

<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>
于 2013-01-14T19:31:58.553 回答
-1

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

表单发布到的 php 文件使用 $_POST 接收它,在 geoit 的情况下是 $_POST['geographic'],状态也是如此。现在您知道如何访问该值,您可以验证它。

所以

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

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

}
于 2013-01-14T18:41:37.813 回答