1

here is the code sample: HTML:

 <form id="information" name="information" action="#" method="post"> 
 <textarea name="text" rows="10" cols="10"> 
 </textarea> 
 <input type="submit" value="submit"/> 
 </form> 

Javascript:

 window.onload=init;

 function init(){
 document.getElementById('information').onsubmit=validateForm;
 }

 function validateForm(){ 
 var text= document.information.text.value; 
 if(text==""){ 
 alert('text area cannot be empty');
 return false;
 } 
 }

it does not work...

3 Answers 3

5

You've got a carriage return in your textarea - so its value is \n or \r\n
close your tag on the same line

Edit:
You could strip the beginning and end whitespace using this function

function trim( str ) {
    return str.replace( /^\s+|\s+$/g, '' );
}
Sign up to request clarification or add additional context in comments.

1 Comment

exactly, he's right. If you don't specify anything you don't have the textarea's value property equal to "".
2

The textarea has a carriage return in it (and a space), so your condition is never true. So change it to:

<textarea name="text" rows="10" cols="10"></textarea> 

However you may want to go further and stop the user entering an "empty" response (meaning nothing but white-space). Or you may just want to remove leading and trailing white-space. If so you can do this:

text = text.trim();

Now trim() I believe is relatively new (Firefox lists it as new in 3.5). A more backwards compatible version is:

text = text..replace(/^\s\s*/, '').replace(/\s\s*$/, '');

and then testing if it's empty.

Faster JavaScript Trim has a good analysis on various white-space trimming alternatives. For instance the above can be done with one regex:

text = text..replace(/^\s+|\s+$/g, '');

but

This commonly thought up approach is easily the most frequently used in JavaScript libraries today. It is generally the fastest implementation of the bunch only when working with short strings which don't include leading or trailing whitespace. This minor advantage is due in part to the initial-character discrimination optimization it triggers. While this is a relatively decent performer, it's slower than the three methods above when working with longer strings, because the top-level alternation prevents a number of optimizations which could otherwise kick in.

Comments

0

This worked for me:

function validateForm(){
  var text = document.information.text.value;
  if(text == " \n "){
    alert("Error");
    return false;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.