gpt4 book ai didi

Javascript 表单验证不为空或没有空格

转载 作者:可可西里 更新时间:2023-11-01 13:09:20 25 4
gpt4 key购买 nike

我正在尝试验证我正在创建的表单,但似乎无法理解它是如何工作的。我正在尝试确保该字段不为空或不包含空格我已经在服务器端而非客户端对其进行了验证。

有人可以给我看下面的代码来验证是否为空或没有空格吗?

我在下面看到这些,这就是我认为他们所做的:

x===null // means if field is empty
x==="" // on trying this means if the field is empty
x===" " // and this checks if there is 1 white space

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x===null || x===""|| x===" ") {
alert("First name must be filled out");
return false;
}
}
</script>
</head>

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>

</html>

最佳答案

您可以使用 javascript trim() 函数执行此操作。

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x.trim()==null || x.trim()==""|| x===" ") {
alert("First name must be filled out");
return false;
}
}
</script>
</head>

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>

</html>

关于Javascript 表单验证不为空或没有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27543671/

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