空输入字段的 JavaScript 验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3937513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript validation for empty input field
提问by Eyla
Greeting,
I have this input field
<input name="question"/>
I want to call IsEmpty function when submit clicking submit button.
问候,我有这个输入字段,
<input name="question"/>
我想在提交单击提交按钮时调用 IsEmpty 函数。
I tried the code below but did not work. any advice?!
我尝试了下面的代码,但没有用。有什么建议吗?!
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=unicode" />
<meta content="CoffeeCup HTML Editor (www.coffeecup.com)" name="generator" />
</head>
<body>
<script language="Javascript">
function IsEmpty() {
if (document.form.question.value == "") {
alert("empty");
}
return;
}
</script>
Question: <input name="question" /> <br/>
<input id="insert" onclick="IsEmpty();" type="submit" value="Add Question" />
</body>
</html>
回答by Sk Mourya
<script type="text/javascript">
function validateForm() {
var a = document.forms["Form"]["answer_a"].value;
var b = document.forms["Form"]["answer_b"].value;
var c = document.forms["Form"]["answer_c"].value;
var d = document.forms["Form"]["answer_d"].value;
if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {
alert("Please Fill All Required Field");
return false;
}
}
</script>
<form method="post" name="Form" onsubmit="return validateForm()" action="">
<textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
<textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
<textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
<textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>
回答by Sarfraz
See the working example here
请参阅此处的工作示例
You are missing the required <form>
element. Here is how your code should be like:
您缺少所需的<form>
元素。您的代码应该如下所示:
function IsEmpty() {
if (document.forms['frm'].question.value === "") {
alert("empty");
return false;
}
return true;
}
<form name="frm">
Question: <input name="question" /> <br />
<input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question" />
</form>
回答by Roko C. Buljan
An input field can have whitespaces, we want to prevent that.
Use String.prototype.trim():
输入字段可以有空格,我们想防止这种情况。
使用String.prototype.trim():
function isEmpty(str) {
return !str.trim().length;
}
Example:
例子:
const isEmpty = str => !str.trim().length;
document.getElementById("name").addEventListener("input", function() {
if( isEmpty(this.value) ) {
console.log( "NAME is invalid (Empty)" )
} else {
console.log( `NAME value is: ${this.value}` );
}
});
<input id="name" type="text">
回答by Atif Tariq
I would like to add required attribute in case user disabled javascript:
如果用户禁用了 javascript,我想添加 required 属性:
<input type="text" id="textbox" required/>
It works on all modern browsers.
它适用于所有现代浏览器。
回答by Jak Samun
if(document.getElementById("question").value.length == 0)
{
alert("empty")
}
回答by Rajat
Add an id "question" to your input element and then try this:
向输入元素添加一个 id“问题”,然后尝试以下操作:
if( document.getElementById('question').value === '' ){
alert('empty');
}
The reason your current code doesn't work is because you don't have a FORM tag in there. Also, lookup using "name" is not recommended as its deprecated.
您当前的代码不起作用的原因是那里没有 FORM 标记。此外,不推荐使用“名称”进行查找,因为它已被弃用。
See @Paul Dixon's answer in this post : Is the 'name' attribute considered outdated for <a> anchor tags?
请参阅这篇文章中@Paul Dixon 的回答:<a> 锚标记的“名称”属性是否已过时?
回答by Kenneth J
if(document.getElementById("question").value == "")
{
alert("empty")
}
回答by Bal
Just add an ID tag to the input element... ie:
只需在输入元素中添加一个 ID 标签...即:
and check the value of the element in you javascript:
并检查javascript中元素的值:
document.getElementById("question").value
document.getElementById("问题").value
Oh ya, get get firefox/firebug. It's the only way to do javascript.
哦,是的,获取 firefox/firebug。这是做javascript的唯一方法。
回答by Ravindra Bohra
<pre>
<form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form>
</pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name", "req", "Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.jsfile
在使用上面的代码之前,你必须添加gen_validatorv31.js文件
回答by Kingston Fortune
My solution below is in es6 because I made use of const
if you prefer es5 you can replace all const
with var
.
我下面的解决方案是在 es6 中,因为我利用了const
如果您更喜欢 es5,您可以将所有替换const
为var
.
const str = " Hello World! ";
// const str = " ";
checkForWhiteSpaces(str);
function checkForWhiteSpaces(args) {
const trimmedString = args.trim().length;
console.log(checkStringLength(trimmedString))
return checkStringLength(trimmedString)
}
// If the browser doesn't support the trim function
// you can make use of the regular expression below
checkForWhiteSpaces2(str);
function checkForWhiteSpaces2(args) {
const trimmedString = args.replace(/^\s+|\s+$/gm, '').length;
console.log(checkStringLength(trimmedString))
return checkStringLength(trimmedString)
}
function checkStringLength(args) {
return args > 0 ? "not empty" : "empty string";
}