Javascript textarea的验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2521559/
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
Validation of textarea
提问by Hulk
How to do I validate a textarea in a form? i.e, it should not be empty or have any new lines, and if so raise an alert.
如何验证表单中的文本区域?即,它不应为空或有任何新行,如果是,则发出警报。
Code:
代码:
<script>
function val()
{
//ifnewline found or blank raise an alert
}
</script>
<form>
<textarea name = "pt_text" rows = "8" cols = "8" class = "input" WRAP ></textarea>
<input type=""button" onclick="val();"
</form>
回答by Sarfraz
Try this:
尝试这个:
<textarea id="txt" name = "pt_text" rows = "8" cols = "8" class = "input" WRAP ></textarea>
function val()
{
if (trimAll(document.getElementById('txt').value) === '')
{
alert('Empty !!');
}
}
function trimAll(sString)
{
while (sString.substring(0,1) == ' ')
{
sString = sString.substring(1, sString.length);
}
while (sString.substring(sString.length-1, sString.length) == ' ')
{
sString = sString.substring(0,sString.length-1);
}
return sString;
}
回答by Esteban
The easiest way I could think of:
我能想到的最简单的方法:
function validate() {
var val = document.getElementById('textarea').value;
if (/^\s*$/g.test(val) || val.indexOf('\n') != -1) {
alert('Wrong content!');
}
}
回答by raj
<script>
function val()
{
if(document.getElementById("textAread_id").value==null || document.getElementById("textAread_id").value=="")
alert("blank text area")
}
</script>
<form>
<textarea id="textAread_id" name = "pt_text" rows = "8" cols = "8" class = "input" WRAP ></textarea>
<input type=""button" onclick="val();"
</form>
回答by Darin Dimitrov
First give your textarea an unique identifier allowing you to easily obtain reference to it:
首先为您的 textarea 提供一个唯一标识符,以便您轻松获取对它的引用:
Then you could test if it contains a new line or it is empty like so:
然后你可以测试它是否包含一个新行或者它是空的,如下所示:
function val() {
var el = document.getElementById('pt_text');
if (el == null) {
// no element with given id has been found
return;
}
var value = el.value;
if (value == null || value === '' || value.indexOf('\n') > 0) {
alert('empty or contains a new line');
}
}
回答by RubyDubee
<html>
<head>
<script type="text/javascript">
function val(value){
if(value.length == 0)
alert("thsi is empty");
}
</script>
</head>
<body>
<textarea id="text"></textarea>
<button onclick="val(text.innerHTML);">Check</button>
</body>
</html>
This is to check if the textarea is empty
这是为了检查 textarea 是否为空

