devxlogo

Handling Single Quotes in Values From ASP

Handling Single Quotes in Values From ASP

Question:
How can I prevent sending the contents of a form field containing single quotes to the server? Single quotes should be converted to double quotes in a way that doesn’t give any problems when writing to the database.

Answer:

Just make sure that before you pass the data back to the database, you check the string for any improper values. One good way is to create a function called CheckString on your ASP page. This function would convert all occurrences of single quotes to two single quotes that should have no problem in your database. You can then call this function before passing the values to the database.

Function CheckString(byval strText)   ' -- this function converts all single quotes   ' -- inside 'strText' to two single quotes and   ' -- also encloses the entire 'strText' string   ' -- within single quotes   CheckString = "'" & Replace(strText, "'", "''") & "'"End Function

One problem with this code is that it relies on the VBScript Replace function to do the actual replacement. Memory leaks have occurred with the Replace function (hopefully they will be fixed in the future). If you do not wish to rely on the Replace function, you can use this second version of the CheckString function that does a brute force replacement.

Function CheckString(byval strText)   Dim intPos   intPos = InStr(strText, "'")   While intPos > 0      strText = Left(strText, intPos) & _                "'" & _                Mid(strText, intPos + 1)      intPos = Instr(intPos+2, strText, "'")   Wend   CheckString = "'" & strText & "'"End Function

Now, in your ASP page, assuming that you obtained the value of a form field into a variable called strAddress, you would “clean up” the variable before passing it over to the database.

   strAddress = CheckString(strAddress)

Note: If you do not want the CheckString function to enclose the string within single quotes, you can modify the code so it does not do so. Also, if you want single quotes to be replaced by any other character, you can modify the code to do so.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist