简体   繁体   English

HTML表单的Java验证无效

[英]Javascript validation for html form not working

I'm trying to make a working javascript validator for an HTML form for an assessment, I have gotten the lecturer to help me originally, however they could not solve the issue. 我正在尝试为HTML表单制作一个可工作的javascript验证器以进行评估,我最初得到了讲师的帮助,但是他们无法解决问题。 The validation works until I add another input to validate then it completely stops working. 验证有效,直到我添加另一个输入进行验证,然后完全停止工作。 I am new to javascript, i have never worked with it before. 我是javascript新手,以前从未使用过它。

I have tried rebuiling the validator and order form completely multiple times. 我已经尝试过多次重新建立验证程序和订购表。 I have reviewed the code multiple times to no avail. 我已多次审查该代码,但无济于事。

 function validateForm() { var x = document.forms["myForm"]["fname"].value; if (x == " ") { alert("Name must be filled out"); return false; } var y = document.forms["myForm"]["mname"].value; if (y == " ") { alert("middle name must be filled out"); return false; } } 
 <script src="Validator.js"></script> <form name="myForm" onsubmit="return validateForm()" action="OrderConfirmed.htm" method="post"> Name: <input type="text" name="fname" value=" "> Middle Name: <input type="text" name="mname" value=" "> <input type="submit" value="Submit"> </form> 

The expected result is that when the form is submitted but a field is empty a message (dialog box) should be displayed telling the user which input is not filled in. 预期结果是,在提交表单但字段为空时,将显示一条消息(对话框),告诉用户未填写哪个输入。

You could solve it by using 'event.preventDefault'. 您可以使用“ event.preventDefault”解决它。 (But your code should work too...) Here is example code: (但是您的代码也应该工作...)这是示例代码:

 <html> <head> </head> <body> <form name="myForm" onsubmit="validateForm(event)"> Name: <input type="text" name="fname" value=" "> Middle Name: <input type="text" name="mname" value=" "> <input type="submit" value="Submit"> </form> <script type="text/javascript"> function validateForm(e) { var x = document.forms["myForm"]["fname"].value; if (x == " ") { e.preventDefault(); alert("Name must be filled out"); return false; } var y = document.forms["myForm"]["mname"].value; if (y == " ") { e.preventDefault(); alert("middle name must be filled out"); return false; } } </script> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM