
Javascript: Checking for illegal characters
These functions checks for illegal characters in a form field. The ValidString( ) function does all the work but the others listed below are generic shortcuts for typical functions. They return true or false, you'll have to code in your own alert message in your validation function if these return false.
Example HTML/CFML code:
<script language="Javascript">
// Returns true if the string only contains alpha characters (empty string = true)
function isAlpha(txt)
{
return ValidString(txt,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
}
// Returns true if the string only contains numeric characters (empty string = true)
function isNumeric(txt)
{
return ValidString(txt,'0123456789');
}
// Returns true if the string only contains alpha numeric characters (empty string = true)
function isAlphaNumeric(txt)
{
return ValidString(txt,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
}
// Returns true if the CheckString only contains characters passed in ValidString (empty string = true)
function ValidString(ChkString,ValidString)
{
for (i=0; i<ChkString.length; i++)
{
if (ValidString.indexOf(ChkString.substring(i,i+1)) == -1) return false;
}
return true;
}
function SubmitForm()
{
if (!isAlpha(document.Test.Alpha.value)) { alert('Alpha Only must only contain A-Z or a-z');return }
if (!isAlphaNumeric(document.Test.AlphaNumeric.value)) { alert('Alpha Numeric must only contain A-Z, a-z, or 0-9'); return }
if (!isNumeric(document.Test.Numeric.value)) { alert('Number must only contain 0-9'); return }
alert('All is okay!');
}
</script>
<form name="Test">
Alpha Only: <input type="Text" name="Alpha" value=""><br>
Alpha Numeric Only: <input type="Text" name="AlphaNumeric" value=""><br>
Numeric Only: <input type="Text" name="Numeric" value=""><br>
<input type="Button" value="Go!" onClick="SubmitForm()">
</form>
Return to the Cold Fusion Tips-N-Tricks topic list