ASP - Active Server Pages
Sanitize or clean price / cost field for database insertion or display
If you need to deal with price/cost fields, you may need to server-side check the validity of the form input for the field, or manipulate the numeric string. Place numbers or text into the box to see a demonstration.
I asked Benj Clews (who does Four Word Film Review) to critique this code and he wrote a leaner, more efficient function. View it.
| Here is how I set up my PRICE field in the
database.
|
| Here is this page's html
and ASP code: <% dim strOurValue strOurValue = request.form("PRICE") 'Let's sanitize our Price field 'OK let's first make sure the price string is numeric if NOT isNumeric(strOurValue) then response.write "Not a number." ' you could put in code to remove nonnumeric characters strOurValue = null 'if not numeric let's set the value to null or use 0 if you want else strDec = strOurValue 'let's see if there is a decimal in the string and what place it is in strDec = inStr(strDec,".") if strDec >0 then NumArray = Split(strOurValue, ".") 'if numeric let's split the price string where the decimals are str1 = NumArray(0) 'this is the numbers to the left of the decimal str2 = NumArray(1) 'this is the numbers on the other side of the decimal str2 = Left(str2,2) 'let's take only the left two numbers of the second set in the array strOurValue = str1 & "." & str2 'let's put the sets back together to make a clean price string. That is the value that I would insert into the database field. 'I would use the code below to display the value. strOurValue = formatnumber(strOurValue)'let's format as currency end if end if if strDec < 1 then strOurValue = strOurValue & ".00" end if if strDec <>"" then response.write "<br>The sanitized Price is: $" &strOurValue ' and write it out end if %> <form method="POST" action="decimaltest.asp"> |