开发者

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>


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.


<script>
    function val()
    {
      if(document.getElementById("textAread_id").value==null || document.getElementById("textAread_id").value=="")
alert("blank text area")
    } 
   </script>
   <form>  
   <textarea id="textAread_id" name = "pt_text" rows = "8" cols = "8" class = "input" WRAP ></textarea>
   <input type=""button" onclick="val();"
    </form>


First give your textarea an unique identifier allowing you to easily obtain reference to it:

Then you could test if it contains a new line or it is empty like so:

function val() {
    var el = document.getElementById('pt_text');
    if (el == null) {
        // no element with given id has been found
        return;
    }
    var value = el.value;
    if (value == null || value === '' || value.indexOf('\n') > 0) {
        alert('empty or contains a new line');
    }
}


<html>
<head>
<script type="text/javascript">
   function val(value){
      if(value.length == 0)
         alert("thsi is empty");
   }
</script>
</head>
<body>
<textarea id="text"></textarea>
<button onclick="val(text.innerHTML);">Check</button>
</body>
</html>

This is to check if the textarea is empty

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜