简单验证也无效

时间:2016-03-06 09:03:50

标签: javascript html validation

这是我简单的HTML代码。我在这个html文件中包含了javascript。我想在名称上执行验证,如没有空字段和数据格式验证,但它无法正常工作。有人可以帮我摆脱这个

  <html>
  <head>
  <title>Aptitude Competition Online</title>
  <link rel="stylesheet" type="text/css" href="index.css">
  <script type="text/javascript">
  function validate()
  {  
  var nam = document.forms[0].name.value; 
    if(nam == "") 
     { 
         alert("Name should be filled out"); 
         document.getElementById("name").focus;
         return false;
     } 
    else {  
         return true; 
         } 
   }
  </script> 
</head>
<body>
<div id="header1">
<font id="font1">Aptitude Quiz</font>
</div>
<div id="bgr">
<div id="emal">
<font style="position:absolute;top:16px;left:100px;font-size:20px;">Welcome     to Aptitude Quiz</font><br><br><br
<form name="form">
 Name : <input type="text" name="name" id="name"><br><br>
 <input name="Participate" type="button" value="Participate"  onClick="validate()" >
 </form>

  </div>
 </div>
  <div id="footer">
   Contact Us : gmail@name.com 
   </div>
    </body>
   </html>

1 个答案:

答案 0 :(得分:4)

您的HTML代码中存在错误。您忘记在<br>

之前关闭<form name='form'>代码

此外,“焦点”是一种方法,而不是一种属性。我已经添加了

这是更正后的代码。

<html>

<head>
    <title>Aptitude Competition Online</title>
    <link rel="stylesheet" type="text/css" href="index.css">
    <script type="text/javascript">
        function validate() {
            var nam = document.forms[0].name.value;
            if (nam == "") {
                alert("Name should be filled out");
                document.getElementById("name").focus();
                return false;
            } else {
                return true;
            }
        }
    </script>
</head>

<body>
    <div id="header1">
        <font id="font1">Aptitude Quiz</font>
    </div>
    <div id="bgr">
        <div id="emal">
            <font style="position:absolute;top:16px;left:100px;font-size:20px;">Welcome     to Aptitude Quiz</font>
            <br>
            <br>
            <br> <form name="form"> Name :
            <input type="text" name="name" id="name">
            <br>
            <br>
            <input name="Participate" type="button" value="Participate" onClick="validate()">
            </form>

        </div>
    </div>
    <div id="footer">
        Contact Us : gmail@name.com
    </div>
</body>

</html>