[英]how to validate a textarea using javascript
I want to check a textarea whether it is empty or not. 我想查看textarea是否为空。 For this I write the following code: 为此我写了以下代码:
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if (problem_desc.value == '') {
alert("Please Write Problem Description");
return false;
} else {
return true;
}
}
For the first time it is working fine. 这是第一次工作正常。 But If I remove the text from the textarea the above function is returning true value ie, it is assuming the previous text I've entered into the textbox. 但是如果我从textarea中删除文本,则上面的函数返回true值,即,它假定我之前输入文本框的文本。 Can anybody kindly tell me where is the problem? 任何人都可以告诉我问题出在哪里?
I am getting it correctly. 我正确地得到它。 This is what I did. 这就是我做的。
Please Write Problem Description
. 点击验证,它说Please Write Problem Description
。 Please Write Problem Description
. 点击验证,它说Please Write Problem Description
。 Note: Use a trim
function to eliminate empty spaces. 注意:使用trim
函数消除空格。
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if ($.trim(problem_desc.value) == '') {
alert("Please Write Problem Description");
return false;
} else {
return true;
}
}
Do check for white space in the value like this 请检查这样的值中的空格
if (problem_desc.value.match (/\S/)) { ... }
or other way check for length 或其他方式检查长度
problem_desc.value.length == 0;
Remove spaces and calculate length of the value attribute. 删除空格并计算value属性的长度。
function validateForm(theForm) { var problem_desc = document.getElementById("problem_desc"); if (problem_desc.value.replace(/ /g,'').length) { return true; } else { alert("Please Write Problem Description"); return false; } }
<textarea id="problem_desc"></textarea> <button onclick="validateForm()">Validate</button>
我会说你更好修剪,然后检查空格的长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.