我的Java HTML表单验证程序似乎不起作用

问题描述 投票:0回答:2

我对javascript还是很陌生,所以请和我一起裸露。但是我不确定HTML会出错,尽管我为HTML编写了一个验证器。

我在下面尝试做的是确定“名字”框中是否有任何文本。该代码包含基本的CSS,但是我认为我的问题围绕在onsubmit和validate函数上,因为一旦单击“提交”按钮,javascript中的任何内容似乎都无法运行。

<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8">
	<title>NewPatientForm</title>
	<link rel="stylesheet" type="text/css" href="NewPatient.css">
	
	<script>
		function validate() {
    var invalid = false;


    if(!document.Firstname.value.length) {
        invalid = true;
    }
	
    if(invalid) {
        document.getElementById("form-error").style.display = "inline-block";
        return false; //to make the text appear
    }
    return true;
}

	</script>
</head>
<body>
  <form id="NewPatientForm" method="post" action="#" onsubmit="return  validate();">
  <div class="form-element">
	<p id="form-error">All fields are required</p>
  </div>
  
  <div>
  <label for="Firstname">First Name
	<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
	</label>
  </div>

  <div>
	<input type="submit" name="submit-button" value="Submit">
  </div>
  </form>
</body>
</html>
javascript html onsubmit
2个回答
0
投票

有一些错别字,我也会建议其他一些东西。首先,在代码中修复一个或三个:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>NewPatientForm</title>

  <script>
    function validate() {
      const invalid = document.getElementById("Firstname").value.length == 0;
      if(invalid) {
        document.getElementById("form-error").style.display = "inline-block";
        return false; //to make the text appear
      }
      return true;
    }

  </script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
    <div class="form-element">
        <p id="form-error">All fields are required</p>
    </div>

    <div>
        <label for="Firstname">First Name
            <input type="text" name="Firstname" placeholder="First Name" id="Firstname">
        </label>
    </div>

    <div>
        <input type="submit" name="submit-button" value="Submit">
    </div>
</form>
</body>
</html>

我的建议是,您还要研究内置的HTML表单验证属性。我认为您正在重新设计轮子,例如要求使用非空的名字。为什么不使用它而不是JavaScript?

<input type="text" name="Firstname" id="Firstname" placeholder="First Name" required />

还有许多其他名称,例如minlength =“”,min =“”,step =“”等。>

此外,还有一个JavaScript钩子使用.checkValidity()插入验证系统,因此您可以让内置验证完成繁重的工作,然后再添加更多您自己的自定义方面。


0
投票

看起来像是罪魁祸首是您尝试访问Firstname对象上的document

© www.soinside.com 2019 - 2024. All rights reserved.