javascript空字段表单验证无效

时间:2013-01-31 10:55:20

标签: javascript validation

您好我是javascript的新手。

我正在尝试实现一些javascript表单验证 我试图使用这里使用的技术: http://www.w3schools.com/js/tryit.asp?filename=tryjs_form_validation 测试表单中的空字段并使用警报来警告用户 但它对我不起作用 当我提交一个空表单继续jsp文件并且javascript没有捕获错误

这是我的index.html文件,表单是

<html>
  <body>
    <head>
    <script>
        function validateForm()
        {
            var stoneField=document.forms["bmiForm"]["stone"].value;
            var poundsField=document.forms["bmiForm"]["pounds"].value;
            var kgsField=document.forms["bmiForm"]["kgs"].value;
            var feetField=document.forms["bmiForm"]["feet"].value;
            var inchesField=document.forms["bmiForm"]["inches"].value;

            if ( stoneField = null || stoneField = "" && poundsField = null || poundsField = "" && kgsField = null || kgsField = "" && feetField = null || feetField = "" && inchesField = null || inchesField = "" )
            {
              alert("Please enter a weight and height");
              return false;
            }
            else
            {

             return true;
            } 
        }
    </script>
</head>
<form name ="bmiForm" action="PrintBMI.jsp" onsubmit="return validateForm()" method=post  style="width:250px;">
    <fieldset>
    <legend>BMI Calculator</legend>
    <h3>Enter your weight</h3>
    Stone <input type = text name = "stone" size = 1 maxlength = 2>
    Pounds <input type = text name = "pounds" size = 1 maxlength = 2>
    <br>
    <strong>OR</strong>
    <br>
    KGs <input type = text name = "kgs" size = 1 maxlength = 3>

    <h3>Enter your height</h3>
    Feet <input type = text name = "feet" size = 1 maxlength = 1>
    Inches <input type = text name = "inches" size = 1 maxlength = 2>
    <br>
    <strong>OR</strong>
    <br>
    Metres <input type = text name = "metres" size = 1 maxlength = 4>
    <p><input type=submit value = "Get BMI">
    </fieldset>
</form>
</body>
</html>'

有谁看到我做错了什么。谢谢你的时间。

3 个答案:

答案 0 :(得分:1)

在此代码中将=替换为===

if ( stoneField = null || stoneField = "" && poundsField = null || poundsField = "" && kgsField = null || kgsField = "" && feetField = null || feetField = "" && inchesField = null || inchesField = "" )

了解Comparison Operators

答案 1 :(得分:0)

if ( stoneField = null || stoneField = "" && poundsField = null || poundsField = "" && kgsField = null || kgsField = "" && feetField = null || feetField = "" && inchesField = null || inchesField = "" )
        {
          alert("Please enter a weight and height");
          return false;
        }

使用=== inside if,not =

答案 2 :(得分:0)

USE ==用于比较价值。

替换代码中的下面的代码块。

if ( stoneField == null || stoneField == "" && poundsField == null || poundsField == "" && kgsField == null || kgsField == "" && feetField == null || feetField == "" && inchesField == null || inchesField == "" )