javascript空字段表单验证不起作用

标签 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>'

有人看到我做错了什么吗?感谢您抽出时间。

最佳答案

将以下代码中的 = 替换为 ===:

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

了解Comparison Operators

关于javascript空字段表单验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14624050/

相关文章:

Javascript:通过检查对象的属性从数组中删除对象

javascript - 为什么设置你无法获得的属性(property)是合法的?

html - 为什么输入:invalid true when the input is empty?

json - JSON验证是最佳做法吗?

javascript - 如何从返回 JSON 的 REST Web 服务加载 ng 表中的数据

javascript - 如何使用javascript计算html表格行

validation - angular2 自定义模板验证器具有过时值

validation - 是的 vs Joi 进行前端验证

php - 如何限制功能并包含php脚本可以运行?

javascript - 如何使用 "in"和/或 "hasOwnProperty"缩小对象类型