javascript 如何使用javascript验证textarea

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12635489/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:44:14  来源:igfitidea点击:

how to validate a textarea using javascript

javascript

提问by user1407310

I want to check a textarea whether it is empty or not. For this I write the following code:

我想检查一个 textarea 是否为空。为此,我编写了以下代码:

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 i.e., it is assuming the previous text I've entered into the textbox. Can anybody kindly tell me where is the problem?

这是第一次它工作正常。但是,如果我从 textarea 中删除文本,则上述函数将返回真值,即,它假定我已在文本框中输入了先前的文本。有人可以告诉我问题出在哪里吗?

回答by Praveen Kumar Purushothaman

I am getting it correctly. This is what I did.

我正确地得到它。这就是我所做的。

  1. Click on validate, it said Please Write Problem Description.
  2. Write something and click. Nothing happened.
  3. Remove the text. Click on validate, it said Please Write Problem Description.
  1. 点击验证,它说Please Write Problem Description
  2. 写一些东西并点击。没啥事儿。
  3. 删除文本。点击验证,它说Please Write Problem Description

Note: Use a trimfunction to eliminate empty spaces.

注意:使用trim函数消除空格。

Code:

代码:

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;
    }
}

Demo: http://jsfiddle.net/TZGPM/1/(Checks for Whitespaces too!)

演示:http: //jsfiddle.net/TZGPM/1/ (也检查空格!)

回答by Pranay Rana

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; 

回答by Netham

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>

回答by Chandra Sekhar Walajapet

i would say you better trim and then check the length for empty spaces.

我会说你最好修剪一下,然后检查空白处的长度。