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>
                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!');
    }
}
                        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;
}
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With