JavaScript 中 float 和非空的验证

我是网络开发领域的新手,我从基本的应用程序开始。我正在制作一个简单的网页来添加两个数字,并尝试执行一些基本验证,输入字段不能为空,并且输入只能是浮点数。


我的index.html:


<!doctype html>

<html>

<head>

    <!-- Required meta tags -->

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">


    <!-- Bootstrap CSS -->

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="styles.css">

    <link href="https://fonts.googleapis.com/css2?family=Merriweather&display=swap" rel="stylesheet">

    <title>Add Two Numbers</title>

</head>

<body>

    <form class="container center_div topSpacing">

        <h1 id="Title" class="text-center">Add Two Numbers</h1> 

        <div class="form-group">

        <label for="Num1">First Number</label>

        <input type="text" class="form-control" id="Num1" placeholder="Enter First Number">

        </div>

        <div class="form-group">

        <label for="Num2">Second Number</label>

        <input type="text" class="form-control" id="Num2" placeholder="Enter Second Number">

        </div>

        <div class="text-center">

            <button onclick="result()" type="button" class="btn btn-outline-success">Evaluate</button>

        </div>

    </form>

    <br>


    <h1 id="Title2" class="text-center"></h1>


    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>

    <script type="text/javascript" src="index.js"></script>

</body>

</html>

我的index.js:


let var1 = document.getElementById("Num1");

let var2 = document.getElementById("Num2");

function validate() {

    if(var1 == "" || var2 == "")

        return false;

    return true;

}


JavaScript 代码不执行验证以及求和。


慕尼黑5688855
浏览 126回答 2
2回答

有只小跳蛙

解决方案的简单解决方法是在输入字段中输入数字。&nbsp;<input type="number" class="form-control" id="Num1" placeholder="Enter First Number">&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp;<input&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type="number"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; class="form-control"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id="Num2"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder="Enter Second Number"&nbsp; &nbsp; &nbsp; &nbsp; />更改验证函数如下&nbsp;function validate() {&nbsp; const reg = /\-?\d+\.\d+/g;&nbsp; if (&nbsp; &nbsp; var1.value !== "" &&&nbsp; &nbsp; var2.value !== "" &&&nbsp; &nbsp; var1.value.match(reg) &&&nbsp; &nbsp; var2.value.match(reg)&nbsp; ) {&nbsp; &nbsp; return true;&nbsp; }&nbsp; return false;}

一只斗牛犬

改变这个function validate() {if(var1 == "" || var2 == "")&nbsp; &nbsp; return false;return true;}到function validate() {if(var1.value == "" || var2.value == "")&nbsp; &nbsp; return false;else&nbsp; &nbsp; return true;}这应该有效。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5