Javascript表单验证部分检查空数据字段是否工作

时间:2013-09-07 10:11:14

标签: javascript html

这是我保存为n_form.html的登录表单。我正在尝试检查空字段,但每当我单击登录而不填写字段时,我的表单重定向到下一页而不是给出消息。请帮忙。

<!DOCTYPE html>
<html>
  <head>
  <title>Registration Form Of Teknack</title>
  <link rel="stylesheet" type="text/css" media="screen" href="css-page.css" />
  <script language="Javascript">
      function validateForm(){
         var x=document.forms["n_form"]["Username"].value;
         var y=document.forms["n_form"]["Password"].value;
         if (x==null || x=="" & y==null || y==" "){
               alert("Form must be filled.");
               return false;
         }
     }
  </script>
  </head>
  <body>
     <br><br><br>
     <form name="n_form" action="form.php"  onclick="return validateForm()"        method="post">      
     <ol>
        <li>Username<br> 
            <input id="width" type="text" name="name" value="" /></li>
    <li><br>Password<br>
        <input id="width" type="password" name="password" value="" /></li>
        <li><br>
            <input type="checkbox" value="">Remember me<br></li>
        <li id="login">
        <br><button type="submit">Login</button></li>
     </ol>
     </form>
  </body>
</html>

提前致谢,

2 个答案:

答案 0 :(得分:1)

尝试:

function validateForm()
{
var x=document.n_form.name.value;
var y=document.n_form.password.value;
 if (x==null || x=="" && y==null || y=="")
 {
alert("Form must be filled.");
return false;
  }
 }

DEMO FIDDLE

答案 1 :(得分:1)

我强烈建议使用jQuery而不是Javascript!学习和学习。不过这是答案:

jQuery验证和表单的教程演示:http://speckyboy.com/2009/12/17/10-useful-jquery-form-validation-techniques-and-tutorials-2/

Javascript中的解决方案:

Javascript代码:

<script language="javascript">
function validateForm(form)
{
 var username=getElementbyId('username').value;
 var password=getElementbyId('password').value;
 if(username == "")
 {
   alert("You must fill up username!");
 }
 else if (password == "")
 {
   alert("You must fill up password!");
 }
 else
 {
   // nothing, okay status...
 }

     // or if you want to show a message on one of empty field:

 if (username == "" || password == "")
 {
   alert("You must fill up a form");
 }
 else
 {
   // nothing, okay status...
 }


}

更改HTML表单:

<li>Username<br>
    <input id="username" type="text" name="username" value="" />
</li>


<li><br>Password<br>
    <input id="password" type="password" name="password" value="" />
</li>

<li><br><input type="checkbox" value="">Remember me<br>
</li>


<li id="login">
    <br><button type="button" onclick="check(this.form)">Login</button>
</li>