2010-03-26 15 views
7

Jak potwierdzić textarea w form.ie, to nie powinno być puste lub mieć żadnych nowych linii, a jeśli tak podnieść alarmWalidacja 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> 

Dzięki

+0

jeśli nie chcesz żadnych nowych linii, dlaczego nie można po prostu użyć pola tekstowego? – kdureidy

Odpowiedz

2

Spróbuj tego:

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

Dzięki, to działa. – svlzx

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

Pierwszy dać textarea unikalny identyfikator pozwala łatwo uzyskać odniesienie do niej:

Następnie można sprawdzić, czy zawiera on nową linię lub jest pusta tak:

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

Uważaj na 'value.indexOf ('\ n')> 0)', 'indexOf' ** zwraca -1, jeśli nie znaleziono **, i ** 0, jeśli pierwszy znak ** w tekście jest nowy linia. – Esteban

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> 

Ma to na celu sprawdzenie, czy obszar tekstowy jest pusty

0

Oto prosty sposób sprawdzania poprawności:

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

And demo.

1

Najprostszym sposobem mogę myśleć:

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

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