View Single Post
  #27 (permalink)  
Old 02-18-2008, 10:15 PM
prasannavigneshr prasannavigneshr is offline
D-Web Incredible
 
Join Date: Feb 2007
Posts: 1,321
prasannavigneshr is on a distinguished road
Send a message via MSN to prasannavigneshr
Thumbs up ColdFusion Tips & Tricks - Javascript: Checking for illegal characters

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:
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>
__________________
Prasanna Vignesh
MCPD | Web Developer
Reply With Quote