Forum Moderators: open

Message Too Old, No Replies

Remove Characters from Input

         

almo136

3:39 pm on Aug 28, 2009 (gmt 0)

10+ Year Member



Hi,

I have a text input which users use to submit a string. I would like to use javascript (jquery) so that if the string contains any & or # these get automatically removed. Does anyone know how to do this?

Thanks

rocknbil

4:30 pm on Aug 28, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



replace?

It's always better to filter data for what you want and throw everything else away. In the below, the regexp throws away everything not (^) a-z, 0-9, and a few other characters.


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- doctype on one line -->
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Untitled</title>
<script type="text/javascript">
function cleanse(form) {
var string='';
if (document.getElementById('in')) {
string = document.getElementById('in').value;
}
if (string == '') { alert('Enter a value'); }
else {
string = string.replace(/[^a-z0-9\s\'\"\-\.\,]+/ig,'');
alert(string);
// uncomment below to submit
//form.submit();
}
return false;
}
</script>
</head>
<body>
<form action="" onSubmit="return cleanse(this);">
<input type="text" name="in" id="in" value="This & that, select # 5, then #10.">
<input type="submit" value="Process">
</form>
</body>
</html>

However, if this is to cleanse data for input to prevent abuse, you're better off doing it via your server side programming as all one has to do is directly query any server programs to get around it, they never have to visit the form (or disable Javascript.)