使用JavaScript和html进行表单验证

Bil*_*lid 1 html javascript php codeigniter

我想验证我的表单.我在我的代码点火器视图中有一个表单验证javascript代码,但它无法正常工作,仍然在没有任何验证的情况下将值发送到下一页.你能告诉我我在哪里弄错了,为什么会这样?

码:

<form method="get" action="/calculator/stage_two" name="calculate" id="calculate" onsubmit="return validateForm();">
    <div class="calc_instruction">
        <input type="text" name="property_number" placeholder="No/Name" id = "property_number" class="stage_one_box" />
        <input type="text"  name="postcode" placeholder="Postcode" id = "postcode" class="stage_one_box" />
    </div>
    <input type = "image" name = "submit_calculator" id = "submit_calculator" value="Go" src = "/images/next_button.png" />
</form>
Run Code Online (Sandbox Code Playgroud)

Javascript功能:

<script type="text/javascript">
    function validateForm() {
        var postcode=document.forms["calculate"]["postcode"].value;
        if (postcode==null || postcode=="") {
            alert("Please enter the postcode to give you more accurate results");
            document.forms["calculate"]["postcode"].focus();
            return false;
        }
</script>
Run Code Online (Sandbox Code Playgroud)

mpl*_*jan 5

你错过了一个结束括号.验证代码中的任何错误都将返回非假值并允许提交

以下是使用表单访问的规范方法:

<form method="get" action="/calculator/stage_two" name="calculate" 
  id="calculate"  onsubmit="return validateForm(this);">
  <div class="calc_instruction">
    <input type="text" name="property_number" placeholder="No/Name" id = "property_number" class="stage_one_box" />
    <input type="text"  name="postcode" placeholder="Postcode" 
      id = "postcode" class="stage_one_box" />
  </div>

    <input type = "image" name = "submit_calculator" id="submit_calculator" src="/images/next_button.png" />
</form>


<script type="text/javascript">
function validateForm(theForm) {
  var postcode=theForm.postcode;

  if (postcode.value=="")  { // cannot be null or undefined if value="" on field
    alert("Please enter the postcode to give you more accurate results");
    postcode.focus();
    return false;
  }
  return true; // allow submit
}
</script>
Run Code Online (Sandbox Code Playgroud)