PDA

View Full Version : How To Detech Special Characters


chchar
09-18-2002, 10:15 AM
How to detect special characters such as - ?<">$% in
Javascript ?

This because I try to avoid user from key in these special
characters in my item description field.

Please advice. Tq.:confused:

glenngv
09-18-2002, 10:30 AM
function check(frm){
val = frm.desc.value;
if (val.indexOf("?")!=-1 || val.indexOf("<")!=-1 val.indexOf('"')!=-1 || val.indexOf(">")!=-1 || val.indexOf("$")!=-1 || val.indexOf("%")!=-1){
alert("These characters are not allowed: ?<\">$%");
frm.desc.focus();
return false;
}
return true;
}

you call this on onsubmit event of the form

<form name="..." onsumbit="return check(this)">

<textarea name="desc"></textarea>
<input type="submit" value="Submit">
</form>

requestcode
09-18-2002, 06:52 PM
Here is an example that will only allow letters and numbers. It also allows the use of the backspace and delete key. When they press the key if it is not valid it will not be allowed. This will check as they press a key rather than waiting untill the form is submitted.
<html>
<head>
<title>regular expression test</title>
<SCRIPT LANGUAGE="JavaScript">
IE = document.all? 1:0;
// If not a through z or A through Z or 0 through 9 then invalid. the "^" stands for not
re3=/[a-zA-Z0-9]/
function checkchar(e)
{
if(IE)
{whKey = event.keyCode}
else
{whKey = e.which}
window.status=whKey
mykey=String.fromCharCode(whKey)
if(whKey==8||whKey==0) // allow backspace key
{return true}
else
{
if(mykey.match(re3))
{return true}
else
{return false}
}
}
</SCRIPT>
</head>
<body bgcolor="lightgreen" onLoad="document.myform.txt1.focus()">
<FORM NAME="myform">
<INPUT TYPE="text" NAME="txt1" SIZE="30" onKeyPress="return checkchar(event)">
</FORM>
</body>
</html>