Friday, September 12, 2008

Remove Invalid Characters Using C#,SQL or Javascript

To provide search your application some time you need to replace invalid Characters from value submitted by user to prevent SQL injection or some other resons.at this time you can do this in three defferent ways.

You can use one of the tree way for remove Special Characters from String as per you search requirement

(1)Javascript

Use Regular Expression For Replacing Invalid Charactervar invalidChars=document.getElementById("txtAllchars").value; document.getElementById("txtAllchars").value=invalidChars.replace(/[^a-zA-Z 0-9]+/,'');

(2).C#:

Yu can Use System.Text.RegularExpression Name spaceUsing RegEx Class You can aloow Only Valida Characters other Invalid Character will be removed

objProperty.ZipCode = Regex.Replace(txtZipCode.Text, "[^A-Za-z0-9]+", "");

(3).SQL.

In SQL There Is Not Direct method To Do this So You Need To Apply Following Code To perform task.

declare @strMain varchar(200) declare @charsToReplace varchar(10) set @charsToReplace ='^&%' set @strMain='Haresh%%^^&&' declare @i int set @i=len(@charsToReplace) while(@i>0) Begin declare @tmp char set @tmp= substring(@charsToReplace,@i,len(@charsToReplace)) set @strMain= replace(@strMain,@tmp,'') set @i=@i-1 End print @strMain