...

View Full Version : validate textarea using javascript



mrjameer
12-21-2006, 07:49 PM
hi,

i want to validate textarea,so that user canot enter words like 'select','*',
'username' ,'password'.how i can stop the user from entering these words using javascript.

thanks
mrjameer

JUD
12-22-2006, 02:18 AM
This will do what you want:



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
// <![CDATA[
var notAllowed = ['select','*','username','password'];

function checkWord(txt){
for(var i = 0; i < notAllowed.length; i++){
if(txt.value.indexOf(notAllowed[i]) != -1){
alert('The word "' + notAllowed[i] + '" is not allowed');
txt.value = txt.value.substr(0, txt.value.indexOf(notAllowed[i]));
break;
}
}
}
// ]]>
</script>
</head>

<body>
<form>
<textarea name="myText" rows="5" cols="20" onkeyup="checkWord(this)"></textarea>
</form>
</body>
</html>

Arbitrator
12-22-2006, 04:00 AM
Hereís another take; I used it as an opportunity to experiment with regular expressions for the first time. Unlike the above, itís case insensitive and doesnít evaluate until submission time.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="Author" content="Patrick Garies"/>
<title>CF 103513 Demo</title>

<!-- Tested: Firefox 2, Internet Explorer 6/7, Opera 9 -->

<style type="text/css">
fieldset {
border: 0 none;
text-align: center;
font-weight: bold;
}
textarea {
display: block;
margin: 0 auto;
}
</style>

<script type="text/javascript">
if (document.addEventListener) {
document.defaultView.addEventListener("load", function() {
document.getElementsByTagName("input")[0].addEventListener("click", validate, false);
}, false);
}
else { /* for Internet Explorer */
window.onload = function() {
document.getElementsByTagName("input")[0].onclick = validate;
}
}
function validate() {
var invalid = /(select|\*|username|password)/i;
var textarea = document.getElementsByTagName("textarea")[0];
var message;
var fieldset = document.getElementsByTagName("fieldset")[0];
if (invalid.test(textarea.value)) {
message = " You canít submit that!";
fieldset.style.color = "red";
}
else {
message = " Thanks!";
fieldset.style.color = "green";
}
fieldset.childNodes[fieldset.childNodes.length - 1].data = message;
}
</script>

</head>
<body>

<fieldset>
<textarea cols="40" rows="4"></textarea>
<input type="submit" value="Submit Query"/>
</fieldset>

</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum