textarea的验证

时间:2010-03-26 06:54:40

标签: html javascript-events javascript

如何验证form.i.e中的textarea,它不应为空或有任何新行,如果是,则提出警报

   <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>

由于

6 个答案:

答案 0 :(得分:2)

试试这个:

<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;
}

答案 1 :(得分:2)

我能想到的最简单的方法:

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

    if (/^\s*$/g.test(val) || val.indexOf('\n') != -1) {
        alert('Wrong content!');
    }
}

答案 2 :(得分:0)

<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>

答案 3 :(得分:0)

首先给textarea一个唯一的标识符,以便您轻松获取对它的引用:

然后你可以测试它是否包含一个新行,或者它是否为空:

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');
    }
}

答案 4 :(得分:0)

<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>

这是检查textarea是否为空

答案 5 :(得分:0)

以下是验证的简单方法:

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

And demo.