gpt4 book ai didi

javascript - 验证表单编号类型 Javascript

转载 作者:行者123 更新时间:2023-12-02 18:20:18 25 4
gpt4 key购买 nike

嗨,我遇到了这个问题。在我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com