8,849
edits
Changes
→See Also
{{JavaScript Syntax}}The following technique can be used to prevent a user from entering special characters in designated form fields[[Custom Fields]].<br>
Special characters can cause problems, particularly when the data is exported to other applications.<br>
==Procedure:==
If you want the replacement to happen actively while the user is typing into the field use ''onKeyup'' instead of ''onChange''.
==Examples==
1. To remove all characters that aren't part of the basic Latin alphabet and 0-9 (such as . , & ; : ~ ! @ # $ % ^ & * ( ) + " ' <u>including the space key<pre/u>function valid) and immediately replace them with an underscore (o_) :{ var re onkeyup=/[&'"]/g othis.value = othis.value.replace(re/[\W]/g,'_');"}</pre>2. The example above following code will remove all & " look for # [ $ ] and ' characters \ and replace them with an underscore (_). If you would rather simple remove once the characters you should use the following as the last line of user has clicked away from the functionfield: o.value = o.value.replace(re,'');
onchange="this.value=this.value.replace(/[#[$\]\\@]/g,'_');"
'''Note''': if you also want to replace double quotes you must omit the double quotes around the javascript statement:
:''onchange=javascript:this.value=this.value.replace(/['@#&"]/g,'_');''
If you want to replace double quotes with a single quote use this:
:''<nowiki>onkeyup=javascript:this.value=this.value.replace(/["]/g,'\'');</nowiki>''
:''<nowiki>onkeyup="this.value=this.value.replace(/[\D]/g,'');"</nowiki>''
[[Category:Custom Fields]][[Category:JavaScript Examples]]