Text validation does not work Javascript

here is a sample code: 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 ...

+1
source share
3 answers

There is a carriage return (and a space) in the text box, so your condition will never be true. Therefore change it to:

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

However, you can go further and prevent the user from entering an "empty" response (which means only empty space). Or you can simply remove the front and back white space. If so, you can do this:

text = text.trim();

Now trim()I consider it relatively new (Firefox lists it as new in version 3.5). More reverse compatible version:

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

and then check if it is empty.

JavaScript . , :

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

JavaScript . , , . . , , , .

+2

, \n \r\n

Edit:
, .

function trim( str ) {
    return str.replace( /^\s+|\s+$/g, '' );
}
+5

This worked for me:

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

All Articles