Solved

ASP Form validation help

Posted on 2007-11-24
34
210 Views
Last Modified: 2010-04-21
hi can anyone help me with asp form validation ( i'm new to this). i have a asp form page which a user will populate and then click the add form which moves to the validation page the code for this is attached, however all i get is a http 500 error can anyone tel me whats going wrong

regards the types, i want a product to have a number of (potentially) differnt types (same with flavours). so i have a list box with all the available types and a second ;ist box with will contain all the types or flavours associated with that product which the user will add to this list. i want to loop through and get all the values held in this second listbox.

( i know i dont actually add to the database yet i know how to do this i just want to test i'm getting all the variable first.)

any ideas?

matt.
<%@LANGUAGE="VBSCRIPT"%>

<%Option Explicit%>

<!--#include file="../../Connections/connection.asp" -->

<!-- #include file="upload.asp" -->

<html>

<head>

<%

' *** Restrict Access To Page: Grant or deny access to this page **********

MM_authorizedUsers="1"

MM_authFailedURL="../admin_access_denied.asp"

MM_grantAccess=false
 

If Session("MM_Username") <> "" Then

  If (false Or CStr(Session("MM_UserAuthorization"))="") Or _

         (InStr(1,MM_authorizedUsers,Session("MM_UserAuthorization"))>=1) Then

    MM_grantAccess = true

  End If

End If

If Not MM_grantAccess Then

  MM_qsChar = "?"

  If (InStr(1,MM_authFailedURL,"?") >= 1) Then MM_qsChar = "&"

  MM_referrer = Request.ServerVariables("URL")

  if (Len(Request.QueryString()) > 0) Then MM_referrer = MM_referrer & "?" & Request.QueryString()

  MM_authFailedURL = MM_authFailedURL & MM_qsChar & "accessdenied=" & Server.URLEncode(MM_referrer)

  Response.Redirect(MM_authFailedURL)

End If

%>
 

<%

'now build up insert string 

Dim supplier = Request.Form("supplier")

Alert(supplier)
 

Dim name = Request.Form("name")
 

Dim prod_types() As String

ReDim prod_types(5)

For i = 1 To Request.Form( "selected_prod_type" ).Count
 

	if(i > UBound(prod_types) then

		ReDim preserve prod_types(i+3)

	end if
 

	prod_types(i) = Request.Form("selected_prod_type" )( i )

Next
 

Dim size = Request.Form("size")
 

Dim brief_des = Request.Form("Brief_des")
 

Dim full_des = Request.Form("full_des")
 

Dim label_info = Request.Form("label_info")
 

Dim directions = Request.Form("directions")
 

Dim rrp = Request.Form("rrp")
 

Dim price = Request.Form("price")
 

Dim flavours() As String

ReDim flavours(5)

For i = 1 To Request.Form( "selected_flavours" ).Count
 

	if(i > UBound(flavours) then

		ReDim preserve flavours(i+3)

	end if
 

	flavours(i) = Request.Form("selected_flavours" )( i )

Next
 

Dim Uploader, File

Set Uploader = New FileUploader
 

' This starts the upload process

Uploader.Upload()
 

If Uploader.Files.Count <> 0 Then
 

	

		File(0).SaveToDisk "..\..\images\thumbs\"

		

		Dim thumbpath = "..\..\images\thumbs\" + File.FileName

		

		File(1).SaveToDisk "..\..\images\images\"

		

		Dim thumbpath = "..\..\images\images\" + File.FileName
 

End if
 
 

%>
 

</head>

</html>

Open in new window

0
Comment
Question by:flynny
  • 18
  • 12
  • 3
34 Comments
 

Author Comment

by:flynny
Comment Utility
also if it helps heres the upload.asp file i found at asp101
<%

'***************************************

' File:	  Upload.asp

' Author: Jacob "Beezle" Gilley

' Email:  avis7@airmail.net

' Date:   12/07/2000

' Comments: The code for the Upload, CByteString, 

'			CWideString	subroutines was originally 

'			written by Philippe Collignon...or so 

'			he claims. Also, I am not responsible

'			for any ill effects this script may

'			cause and provide this script "AS IS".

'			Enjoy!

'****************************************
 

Class FileUploader

	Public  Files

	Private mcolFormElem
 

	Private Sub Class_Initialize()

		Set Files = Server.CreateObject("Scripting.Dictionary")

		Set mcolFormElem = Server.CreateObject("Scripting.Dictionary")

	End Sub

	

	Private Sub Class_Terminate()

		If IsObject(Files) Then

			Files.RemoveAll()

			Set Files = Nothing

		End If

		If IsObject(mcolFormElem) Then

			mcolFormElem.RemoveAll()

			Set mcolFormElem = Nothing

		End If

	End Sub
 

	Public Property Get Form(sIndex)

		Form = ""

		If mcolFormElem.Exists(LCase(sIndex)) Then Form = mcolFormElem.Item(LCase(sIndex))

	End Property
 

	Public Default Sub Upload()

		Dim biData, sInputName

		Dim nPosBegin, nPosEnd, nPos, vDataBounds, nDataBoundPos

		Dim nPosFile, nPosBound
 

		biData = Request.BinaryRead(Request.TotalBytes)

		nPosBegin = 1

		nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(13)))

		

		If (nPosEnd-nPosBegin) <= 0 Then Exit Sub

		 

		vDataBounds = MidB(biData, nPosBegin, nPosEnd-nPosBegin)

		nDataBoundPos = InstrB(1, biData, vDataBounds)

		

		Do Until nDataBoundPos = InstrB(biData, vDataBounds & CByteString("--"))

			

			nPos = InstrB(nDataBoundPos, biData, CByteString("Content-Disposition"))

			nPos = InstrB(nPos, biData, CByteString("name="))

			nPosBegin = nPos + 6

			nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(34)))

			sInputName = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))

			nPosFile = InstrB(nDataBoundPos, biData, CByteString("filename="))

			nPosBound = InstrB(nPosEnd, biData, vDataBounds)

			

			If nPosFile <> 0 And  nPosFile < nPosBound Then

				Dim oUploadFile, sFileName

				Set oUploadFile = New UploadedFile

				

				nPosBegin = nPosFile + 10

				nPosEnd =  InstrB(nPosBegin, biData, CByteString(Chr(34)))

				sFileName = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))

				oUploadFile.FileName = Right(sFileName, Len(sFileName)-InStrRev(sFileName, "\"))
 

				nPos = InstrB(nPosEnd, biData, CByteString("Content-Type:"))

				nPosBegin = nPos + 14

				nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(13)))

				

				oUploadFile.ContentType = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))

				

				nPosBegin = nPosEnd+4

				nPosEnd = InstrB(nPosBegin, biData, vDataBounds) - 2

				oUploadFile.FileData = MidB(biData, nPosBegin, nPosEnd-nPosBegin)

				

				If oUploadFile.FileSize > 0 Then Files.Add LCase(sInputName), oUploadFile

			Else

				nPos = InstrB(nPos, biData, CByteString(Chr(13)))

				nPosBegin = nPos + 4

				nPosEnd = InstrB(nPosBegin, biData, vDataBounds) - 2

				If Not mcolFormElem.Exists(LCase(sInputName)) Then mcolFormElem.Add LCase(sInputName), CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))

			End If
 

			nDataBoundPos = InstrB(nDataBoundPos + LenB(vDataBounds), biData, vDataBounds)

		Loop

	End Sub
 

	'String to byte string conversion

	Private Function CByteString(sString)

		Dim nIndex

		For nIndex = 1 to Len(sString)

		   CByteString = CByteString & ChrB(AscB(Mid(sString,nIndex,1)))

		Next

	End Function
 

	'Byte string to string conversion

	Private Function CWideString(bsString)

		Dim nIndex

		CWideString =""

		For nIndex = 1 to LenB(bsString)

		   CWideString = CWideString & Chr(AscB(MidB(bsString,nIndex,1))) 

		Next

	End Function

End Class
 

Class UploadedFile

	Public ContentType

	Public FileName

	Public FileData

	

	Public Property Get FileSize()

		FileSize = LenB(FileData)

	End Property
 

	Public Sub SaveToDisk(sPath)

		Dim oFS, oFile

		Dim nIndex

	

		If sPath = "" Or FileName = "" Then Exit Sub

		If Mid(sPath, Len(sPath)) <> "\" Then sPath = sPath & "\"

	

		Set oFS = Server.CreateObject("Scripting.FileSystemObject")

		If Not oFS.FolderExists(sPath) Then Exit Sub

		

		Set oFile = oFS.CreateTextFile(sPath & FileName, True)

		

		For nIndex = 1 to LenB(FileData)

		    oFile.Write Chr(AscB(MidB(FileData,nIndex,1)))

		Next
 

		oFile.Close

	End Sub

	

	Public Sub SaveToDatabase(ByRef oField)

		If LenB(FileData) = 0 Then Exit Sub

		

		If IsObject(oField) Then

			oField.AppendChunk FileData

		End If

	End Sub
 

End Class

%>

Open in new window

0
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
Trying removing this line:

  Alert(supplier)

There is no Sub called Alert in the code, and if you are wanting a javascript alert this cannot be contained inside an ASP block.
0
 

Author Comment

by:flynny
Comment Utility
hi,

ok, i've removed this and still get the same error?
0
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
Ensure that the ASP windows account has write permission on the directores it is saving to.
0
 
LVL 11

Expert Comment

by:L00M
Comment Utility
First off, make sure you turn off friendly error messages as found here:

http://www.webwizguide.com/kb/asp_knowledgebase/friendly_HTTP_error_messages.asp

Then load your page again. The error should now be more verbose. Let us know that error and any other important tid bits.

TIA
0
 

Author Comment

by:flynny
Comment Utility
great thanks L00M, thats a big help. at least now i get more meaningful errors!!

ok, i get this now am i declaring the variables wrong?

Microsoft VBScript compilation error '800a0401'

Expected end of statement

Dim supplier = Request.Form("supplier")
-------------^

i've tried Dim supplier As String but this doesnt work either.
0
 

Author Comment

by:flynny
Comment Utility
just to not having simply

supplier =  Request.Form("supplier")

is ok. but if this is right then how will i delcare my array

Dim prodTypes() As String

many thanks for the help in advance!!
0
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
It should be

Dim supplier
supplier = Request.Form("supplier")

The method you tried is for ASP.NET

ASP array functions:
http://www.codefixer.com/tutorials/array_functions.asp
0
 
LVL 11

Expert Comment

by:L00M
Comment Utility
As Rouchie showed, only use:
Dim supplier

In classic ASP, all variables are varient
0
 

Author Comment

by:flynny
Comment Utility
ok great, thanks i'm getting further now ;)

ok i get the following

Request object error 'ASP 0206 : 80004005'

Cannot call BinaryRead

Cannot call BinaryRead after using Request.Form collection.

at the following line

prod_types(i) = Request.Form("selected_prod_type" )( i )

basically i want to pull all the element from the list box "selected_prod_type" on the add page.
0
 
LVL 11

Expert Comment

by:L00M
Comment Utility
Do you have BinaryRead anywhere in your code? Perhaps just before or after that line?
0
 

Author Comment

by:flynny
Comment Utility
no i assume the binary read is the (i) after the Request. the whole code is as follows.

Dim prod_types()
ReDim prod_types(5)
For i = 1 To Request.Form( "selected_prod_type" ).Count

      if(i > UBound(prod_types)) then
            ReDim preserve prod_types(i+3)
      end if
      prod_types(i) = Request.form("selected_prod_type" )( i )
Next

0
 

Author Comment

by:flynny
Comment Utility
if this helps the form on the add page is created as follows

<form action="validateProduct.asp" method="POST" name="add_form" id="add_form" enctype="multipart/form-data">
0
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
I believe this answers the error you are getting.  

http:/Q_20869066.html

You need to collect the posted items in the Uploader object, then refer to them through that instead of request.form

0
 

Author Comment

by:flynny
Comment Utility
great thanks Rouchie thats helped alot almost there now.

i get the following

Object required: '[string: ""]'

for the line

For i = 1 To Uploader.Form( "selected_prod_type" ).Count

is this because the form will only pass the selected entry in the list box. i want to get hold of all the objects in the list box. is this possible?
0
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
>> is this because the form will only pass the selected entry in the list box

Yes, I think so.  Is .Count an actual method of Upload.Form ?  I know Count is used in ASP.NET.
You might have to check that Uploader.Form( "selected_prod_type" ) is not nothing before you do this...

If Uploader.Form( "selected_prod_type" ) <> "" then
   For i = 1 To Uploader.Form( "selected_prod_type" ).Count
   ......
   ......
End If


Or alternatively create an array then use that to loop and count:

Dim prodArray()
prodArray = Split(Uploader.Form( "selected_prod_type" ), ",")
Dim i
For i = 0 to UBound(prodArray)
    .....
    .....
Next
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:flynny
Comment Utility
hi i've tried both method and its appear to only send the highlighted value through ( added a few type and then highlighted one to test this using a response.write).  i can't find much information on uploader.form and doing this. is there any other way you can think of for getting this information?
0
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
>> its appear to only send the highlighted value throug

I would have thought this was the correct behaviour?  Surely you only need to know what values the user has chosen?

Within your form, do you allow theuser to select multiple values in each list?
0
 

Author Comment

by:flynny
Comment Utility
sorry i didn't exlpain it properly. Basically i have two listboxes. the first contains the list of all available product types which i pulled from the db.

the second list box initially is empty and this will contains all the type associated with that product.

i then have an add and remove button which moves the entries betweent eh two. i.e. the user highlights say toys and clicks add toys will be removed from the list of all product types an added to the second list box, with remove doing the reverse.

then when the user clicks the add record button i would like to get hold of all these entrys the users has added to the second list box. does this sound visable?

matt.
0
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
Yes.  There are 2 ways to achieve it.  The first would be the ASP solution and would require 2 hits to the database (1 for each list).  First get all the product types as you are doing, then the second gets all the product types currently assigned to the product.
A further 2 pages would be needed to add/remove entries from each box.  Its a tedious process in classic ASP because you've got to keep hitting the database.

Alternatively, use javascript to copy the list items then save the list box in its populated state.
Here is a page that does what I'm thinking: http://javascript.internet.com/forms/items-popup-list.html
0
 

Author Comment

by:flynny
Comment Utility
hi rouchie thanks for the reply. sorry about the delay in replying.

the javascript version is the way i'm trying to tackle it. the boxes are working fine (i can post the code if you think it'll help) its just passing the data from the form to the validation asp page that i can't do.

so the user has selected all the types they want and moved them into the second list box. (however only the last entry is highlighted.)  they then click ok which will move  submit the form to validate.asp and i need to get hold of all the entries from the second table here.
0
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
If you can post a link to a working example it might be better, or alternatively do a screen grab and highlight what's not working.

Double check that the ASP code that creates the lists (and the javascript too) is creating each list item with a text value (that the user see's), and an ID value (that's stored in HTML in the background).

Then when you do a request.form in the validation page, you should see the ID values in a long string, i.e. "3,46,73,67,78,234"
0
 

Author Comment

by:flynny
Comment Utility
hi Rouchie,

sorry for the delay in replying. ok i've had a look at this like you said. this is what i have

<script language="javascript">
function addOption_all_list(source,dest){
      
      for(i=source.options.length-1;i>=0;i--)
      {
            addOption(dest,source.options[i].text,source.options[i].value);
            removeOption(source,i);
      }
}

function addOption(selectbox,text,value )
{
      var optn = document.createElement("OPTION");
      optn.text = text;
      optn.value = value;
      selectbox.options.add(optn);
}

function removeOption(listbox,i)
{
      listbox.remove(i);
}

function addOption_list(source,dest)
{
      for(i=source.options.length-1;i>=0;i--)      
      {
            if(source.options[i].selected)
            {
                  addOption(dest, source.options[i].text, source.options[i].value);
                  removeOption(source,i);
            }
      }
}


function removeAllOptions(selectbox)
{
      var i;
      for(i=selectbox.options.length-1;i>=0;i--)
      {
            //selectbox.options.remove(i);
            selectbox.remove(i);
      }
}
</script>

in the form i create the list like so

        <select name="prod_type" size="8" id="prod_type">
   
        <%
            Set oRs=Server.CreateObject("adodb.recordset")
            
            strSQL = "SELECT * FROM type ORDER BY type.type"
            
            oRs.Open strSQL, conn
      
            selected = false

            While (NOT oRs.EOF)
                  if(selected=false) then
                        response.write "<OPTION value=" & oRs.Fields.Item("typeid").Value & "SELECTED>" & oRs.Fields.Item("type").Value & "</OPTION>"
                        selected=true
                  else
                        response.write "<OPTION value=" & oRs.Fields.Item("typeid").Value & ">" & oRs.Fields.Item("type").Value & "</OPTION>"
                  end if

                  oRs.MoveNext()
            Wend
        %>
   
      </select>
      <input onclick="addOption_all_list(prod_type,selected_prod_type)" ;="" value="Add All" type="button">
        <input onclick="addOption_list(prod_type,selected_prod_type)" ;="" value="Add &gt;" type="button">
        <input onclick="addOption_list(selected_prod_type,prod_type)" ;="" value="Remove &gt;" type="button">
        <input onclick="addOption_all_list(selected_prod_type,prod_type)" ;="" value="Remove All &gt;" type="button">
        
          <select name="selected_prod_type" size="8" id="selected_prod_type">
          </select>

it just seems to be sending across the highlighted values. (if one is highlighted in the second table.)

any ideas?

thanks again for the help.
0
 

Author Comment

by:flynny
Comment Utility
hi guys just an idea but would i be able to pass an array of hidden fields across
0
 

Author Comment

by:flynny
Comment Utility
alternatively would i be able to create a single hidden field and populate this on the submit click?

so when the form has been filled in and the submit button clicked it call a method which would go through the values and append then together using join to make a long string which coul dbe split on the validation page

e.g type1,type2,..,..., etc.

if not then i could append to the string when the add button is clicked in the java method, however if it was subsequently removed then how would i remove it from the string?
0
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
>> alternatively would i be able to create a single hidden field and populate this on the submit click?

Yes, this is the approach to use.  I don't actually know the javascript to loop through the fields and print their values to a text box, but this would work for sure.


>> f not then i could append to the string when the add button is clicked in the java method, however if it was subsequently removed then how would i remove it from the string?

You get around this problem by only copying the values when the submit button is pressed, not the Add/Remove buttons.  The Add/Remove buttons can *appear* to copy the values as far as the user is concerned, but in actual fact the submit button would loop through the copied values and populate the hidden field when the form was submitted.
0
 

Author Comment

by:flynny
Comment Utility
hi rouchie thanks for the reply.

the first approach would be brilliant.

just to outline (sorry, i'm new to asp) it would i have to call the javascript function on the page when the submit button is clicked and then move to the validate page?

matt.
0
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
Yes that's right.  Let the user do all the Add/Remove actions so the destination list gets populated on their screen.  When they've finished and press Submit, get the javascript to execute and populate the hidden field BEFORE the form actually posts.

You can add an onsubmit event to the <form> tag which runs the script prior to it being submitted:
http://www.w3schools.com/jsref/jsref_onsubmit.asp
http://www.devguru.com/Technologies/ecmaScript/quickref/evhan_onsubmit.html
0
 

Author Comment

by:flynny
Comment Utility
great one last thing then, how can i access the form vairables through this method as i've tried the following (similar to what i was doing before) and its not working. I know tha the method is being called as i've added alert messages to test this, but cannot work out how to access the table.

heres what i have

function submitFormEvent(f)
{
alert("OK IN THE METHOD!!!!");
      alert(f.selected_prod_type.options.length);

      for(i=f.selected_prod_type.options.length-1;i>=0;i--)
      {
            productTypeString = productTypeString + f.selected_prod_type.options[i].text;
            
            alert(productTypeString);
            
            alert(f.selected_prod_type.options[i].text);
      
            if( i+1 < f.selected_prod_type.options.length-1 )
                  productTypeString = productTypeString + ",";
      }
}

where the onsubmit is

"submitFormEvent(this.form)"

oh, and thanks for all your help you've been really patient with this.
0
 
LVL 25

Accepted Solution

by:
Rouchie earned 500 total points
Comment Utility
Actually I've just thought of an even easier way.  The form only posts the entries that are selected, so another trick would be to get javascript to select all the values in the second list when the submit button is pressed.

In the following code, change RETURN FALSE to TRUE to actually post the form after the values have been selected.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>Untitled Page</title>

    <script type="text/javascript">

		/* <![CDATA[ */

		function copyValues() {

			var list = document.getElementById("selectlist");

			if(list){

				for(i=0;i<list.length;i++){

					list.options[i].selected = true;

				}

			}

			return false;

		}

		/* ]]> */

    </script>

</head>

<body>

	<form action="somepage.asp" method="post">

		<p>

			<select id="selectlist" name="selectlist" multiple="multiple">

				<option value="1">Option 1</option>

				<option value="2">Option 2</option>

				<option value="3">Option 3</option>

				<option value="4">Option 4</option>

			</select>

		</p>

		<p>

			<input type="submit" value="Submit" onclick="return copyValues();" />

		</p>

	</form>

</body>

</html>

Open in new window

0
 

Author Comment

by:flynny
Comment Utility
great thanks for you help!
0
 

Author Closing Comment

by:flynny
Comment Utility
brilliant informative comments and ideas and filled in all the holes i needed!
0
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
Thanks :-)
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Have you ever needed to get an ASP script to wait for a while? I have, just to let something else happen. Or in my case, to allow other stuff to happen while I was murdering my MySQL database with an update. The Original Issue This was written…
Adobe Dreamweaver CS5 is a WYSIWYG web page editor that has advanced HTML, CSS, and Javascript rendering functionality and is probably the most well-known HTML editor available. Much of Dreamweaver's appeal centers around the Design View interfac…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now