javascript - 验证表单编号类型 Javascript

标签 javascript html validation

嗨,我遇到了这个问题。在我的 html 代码中,我似乎无法验证我的输入类型“数字”。我使用此代码尝试验证它,但它不起作用

function validateForm()
{
var x=document.forms["form_name"]["number_name"].value;
if (x==null || x=="")
  {
  alert("The following must be filled out");
  return false;
  }
}

我从一个网站获取了这段代码,该网站验证输入类型“文本”而不​​是数字。我正在尝试对我的完整 html 代码实现有效的“数字”验证。顺便说一句,这是我的表格示例:

<form action = "test.php" method = "post" onsubmit = "return validateForm()" name ="form_name">
<input type = "number" min = "0" placeholder = "0" name = "number_name" size = "2"/>

我想知道是否可以使用上面的 javascript valdiation 来验证数字形式,或者是否有更简单的方法来实现。

*深入* 我为第一个问题编写了一个快速的 html 代码,并制作了多种形式的“数字”。它不完整......我决定在实现整个表单的代码之前测试一个“数字” 这是我到目前为止的代码:

<html>
    <head>
    <script language="javascript">
    function validateForm()
    {
    var x=document.forms["order"]["cappuccino_qty"].value;
    if (x >= 0 || x < 0);
    {
    alert("The following must be filled out");
    return false;
    }
    }
    </script>   
    <body>              
    <form action = "test.php" method = "post" onsubmit = "return validateForm()" name ="order">
                <label class = "field" for = "Cappucino">Cappuccino
                <input type = "number" min = "0" placeholder = "$3.75" name = "cappuccino_qty" size = "2"/><br>
                <label class = "field" for = "Espresso">Espresso
                <input type = "number" min = "0" placeholder = "$3.00" name = "espresso_qty" size = "2"/><br>
                <label class = "field" for = "Double Espresso">Double Espresso
                <input type = "number" min = "0" placeholder = "$4.25" name = "double_espresso_qty" size = "2"/><br>
                <label class = "field" for = "Flat White">Flat White
                <input type = "number" min = "0" placeholder = "$3.75" name = "flat_white_qty" size = "2"/><br>
                <label class = "field" for = "Latte">Latte  
                <input type = "number" min = "0" placeholder = "$3.50" name = "latte_qty" size = "2"/><br>
                <label class = "field" for = "Ice Coffee">Ice Coffee
                <input type = "number" min = "0" placeholder = "$2.50" name = "ice_qty" size = "2"/><br>
                <input type = "submit" value = "submit" name = "submit"/>
                <p>
       </form>
       </body>  
       </head>
       </Html>

最佳答案

改变

if (x==null || x=="")

if (/[^\d\.]/.test(x))

检查任何非数字或句点字符(假设您想要允许小数)。

[编辑]

查看更新的 fiddle :http://jsfiddle.net/5UxGp/1/

关于javascript - 验证表单编号类型 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18890912/

相关文章:

reactjs - 如何动态扩展或组合 Yup 模式

jquery - 如何使用 jQuery 验证表单后发送数据?

javascript - ChartJS 和 jsPDF - 为什么背景是黑色的?

javascript - 如何向开发类插入滚动条

javascript - 如何在 Google 跟踪代码管理器中强制使用 SSL

html - 如何在 GWT 1.5 中设置水平拆分器面板的样式

javascript - HTML5,div,隐藏,点击显示

javascript - 在与原始 channel 相同的位置制作克隆 channel

html - 位于右侧的样式下拉菜单

ruby-on-rails - rails 3 : how to generate custom error message from failed validation