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 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


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


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]+", "");


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

1 comment:

Comments posted on ASP.Net Ajax Tutorials Blog are moderated and will be approved only if they are on-topic and not abusive. Please email me or my team for tech-support or blogging related questions. Avoid including website URLs in your comments - Thanks Author