简体   繁体   中英

how to validate a textarea using javascript

I want to check a textarea whether it is empty or not. 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. Can anybody kindly tell me where is the problem?

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 .

Note: Use a trim function to eliminate empty spaces.

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!)

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.

 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> 

我会说你更好修剪,然后检查空格的长度。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM