Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation of textarea

How to do I validate a textarea in a form? i.e, it should not be empty or have any new lines, and if so raise an alert.

Code:

   <script>
    function val()
    {
      //ifnewline found or blank raise an alert
    } 
   </script>
   <form>  
   <textarea name = "pt_text" rows = "8" cols = "8" class = "input" WRAP ></textarea>
   <input type=""button" onclick="val();"
    </form>
like image 537
Hulk Avatar asked Mar 26 '10 06:03

Hulk


3 Answers

The easiest way I could think of:

function validate() {
    var val = document.getElementById('textarea').value;

    if (/^\s*$/g.test(val) || val.indexOf('\n') != -1) {
        alert('Wrong content!');
    }
}
like image 139
Esteban Avatar answered Sep 20 '22 03:09

Esteban


Try this:

<textarea id="txt" name = "pt_text" rows = "8" cols = "8" class = "input" WRAP ></textarea>

function val()
{
  if (trimAll(document.getElementById('txt').value) === '')
  {
     alert('Empty !!');
  }
} 

function trimAll(sString)
{
    while (sString.substring(0,1) == ' ')
    {
        sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length-1, sString.length) == ' ')
    {
        sString = sString.substring(0,sString.length-1);
    }
return sString;
}
like image 23
Sarfraz Avatar answered Sep 24 '22 03:09

Sarfraz


Here is a simple way for validation:

function validate() {
    var val = document.getElementById('textarea').value;
    if (/^\s*$/g.test(val)) {
        alert('Wrong content!');
    }
}

And demo.

like image 24
Minko Gechev Avatar answered Sep 23 '22 03:09

Minko Gechev