user1407310
user1407310

Reputation: 183

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

Upvotes: 3

Views: 20470

Answers (3)

Netham
Netham

Reputation: 1178

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>

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

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

Upvotes: 4

Pranay Rana
Pranay Rana

Reputation: 176896

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; 

Upvotes: 3

Related Questions