Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Specific Style of Form Validation. 2

Status
Not open for further replies.

gwillr

IS-IT--Management
Nov 4, 2003
267
CA
I have a form on a web page that I need to implement some sort of validation. After some research, I decided that javascript is out of the question for this. (users can turn off, bypass if really wanted to among others)

There are only two fields....a name "Name" and email address "EMail"

They currently submit to a DB via odbc dsn connection. using POST , the form is set to submit to the following .asp page:

Code:
<!-- #INCLUDE FILE = "DataStore.inc" -->
<!-- #INCLUDE FILE = "adovbs.inc"    -->
<%
'the purpose of this page is to add users to the database
%>
<%
	'create variable to hold email address
	  DIM EMail
	  Email = Request.Form("EMail")
	  Dim Name
          Name = Request.Form("Name")

	'create variable to hold database object and initialize it
	  Dim objRec
	  Set objRec = Server.CreateObject("ADODB.Recordset")

	'open the database table asptest
	  objRec.Open "test", strConnect, adOpenStatic, _
  	    adLockOptimistic, adCmdTable
    
	'create a new record
	  objRec.AddNew
	'set the field equal to the variable
   	  objRec("EMail") = EMail
	  objRec("Name") = Name
	'update the database with the new record
	  objRec.Update

	'close the database
	  objRec.Close
	  Set objRec = Nothing

	'un-comment this line to point to your desired confirm page
	 Response.Redirect("[URL unfurl="true"]http://www.robarspages.ca/devroot/computersite/aspvalid.asp")[/URL]


%>

SO, WHat I want to do, is have the info validated, hopefully via vbscript or similar. if no errors, the data would go to the processing page as normal....BUT if there are errors in either fields, a line would appear near the field with the problem (on the same page as the form.)

I have done a lot of research and can not find anything concrete, and would appreciate any input. Thanks in advance.

Gary

 
This is what I do.

in my submit button tags
I put
onclick="return validateInput()"

That means before the form is submitted I call a routine called validateInput. If that function returns false the page submittal is aborted.

Then in the function

function validateInput()

{
if document.all.textbox1.value = ""
{
alert("You have not entered a valid textbox1";
document.all.textbox1.focus();
return false;

I have one such block for every element I want to validate. If the validation fails, the cursor goes right back into that box.


 
thanks for the response!

I used to have it set up very much the similar way. I was lookinh to get away from javascript, and use asp code/vbscript.

Gary

 
Page looks like this (pseudocode):
Code:
Set NameValue to ""
Set NameError to ""

Set EmailValue to ""
Set EmailError to ""

Set ErrorFree to True

If Request.Form contains Submit button Then
  If Form(Name) is invalid Then
    Set NameError to "Please enter a valid name."
    Set ErrorFree to False
  End If

  If Form(Email) is invalid Then
    Set EmailError to "Please enter a valid email."
    Set ErrorFree to False
  End If

  If ErrorFree Then
    Store data
    Response.Redirect to Thank You page
  End If

  Set NameValue = Form(Name)
  Set EmailValue = Form(Name)
End If

Write Form HTML
  Form POST to this page

  Name field with value of NameValue
  Red Text with NameError here

  Email field with value of EmailValue
  Red Text with EmailError here

  Submit button with name and value
End Write
First time through -- when the page is first called -- the submit button value won't be in the form object, so it will draw the form normally, with blank values for name and email, and with no error messages because the Error variables are empty.

Upon submission if there is an error in either the name or email, the flag will be thrown and the appropriate error message(s) will be set. When the form is drawn the previously-entered values will be in the form fields and the appropriate error message(s) will be displayed.

Upon submission if there is no error then it will redirect to the Thank You page.

Make sense? Having written about 17 million of these suckers, I can say that it's very straightforward once you've done it a couple of times.
 
Thanks Genimuse, this is exactly what i was thinking.

So to confirm that i have the right understanding....

when user calls up the page, the form fields are blank so page displays as normal.

then, user fills out forms, submits. form action set to POST back to the same page, wehre it is handled by the validator code.

what i dont get is this part (excuse the stupidity)

when the page is first called -- the submit button value won't be in the form object

how is this achieved?

Also, should i create the code for the form using 'response.write'? currently the main form is written in only html.

Gary

 
The lack of submit button is acheived automatically: the user hasn't submitted the form (the page was requested via a GET, by default), so the submit button won't be in Request.Form. It's automagical. :)

I don't use response.write for it, no, because it's hard to maintain and inefficient. My form might look something like this, using the made-up names from my example:
Code:
<%
'do all that ASP stuff here, including setting all of those variables
%>
<form name="form1" method="post" action="thispage.asp">
<input name="Name" type="text" value="<%=NameValue%>"> <font color="red"><%=NameError%></font>
<input name="Email" type="text" value="<%=EmailValue%>"> <font color="red"><%=EmailError%></font>
<input type="submit" name="Submit" value="Send It!">
</form>
And in that ASP block I'd be checking to see if Request.Form("Submit") was equal to "" or not... if it was equal to "" then this is the first time the form has been displayed. If this page was called because the form was submitted to it, then Request.Form("Submit") will be equal to something besides "" -- in my example, it will be equal to "Send It".

You can certainly get fancier, like checking to see if NameError <> "", and if so then writing a more complex eror block, not writing the red font tags if there is none, setting the background of the table cell to red if there is, etc. This is just the basic idea.
 
Here's a validation I was taught that I've showed others that has come in very handy for what I think your trying to do. Simply can add or change to make it work for your site. Make a form called form_validation.asp and copy the below code into the page. This will give you a good example. Hope it helps.

Code:
<%@ Language=VBScript %>
<HTML>
<HEAD>
<style type="text/css">
<!--
.clsNormal { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9px; color: #000000 }
.clsErrorPrompt
{
    FONT-WEIGHT: bold;
    FONT-SIZE: 8pt;
    COLOR: firebrick;
    FONT-FAMILY: Verdana, Arial
}
-->
</style>
</HEAD>

<BODY style="filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr='#ffffff', EndColorStr='#3366ee');">

<%
public const ERRMSG_CENTERSCREEN = "<p align=""center"" class=""clsErrorPrompt"">%1</p>"

'set needed variables connection strings, etc
DIM strName, strNameClass
DIM strEmailAddr, strEmailAddrClass

strName = REPLACE(trim(request("Name")),"'","''")
strEmailAddr = REPLACE(trim(request("strEmailAddr")),"'","''")

strNameClass = "clsNormal"
strEmailAddrClass = "clsNormal"

if len(trim(request("Register"))) > 0 or _
   len(trim(request("Register.x"))) > 0 then

	strErrMsg = "Error encountered:<br>"

	if len(strName) = 0 then
		bError = true
		strNameClass = "clsErrorPrompt"
		strErrMsg = strErrMsg & "Missing Name<br>"
	end if

	if not(IsEmailValid(strEmailAddr)) then
		bError = true
		strEmailAddrClass = "clsErrorPrompt"
		strErrMsg = strErrMsg & "Invalid Email address format<br>"
	end if

	if bError then
		'strErrMsg = strErrMsg & "Please correct the items in red."
	else
		if register(strName, strEmailAddr, strErrMsg) then
			'Log in
			'Call Login(strEmailAddr, strPassword)
			server.transfer("SupportCall.asp")
		else
			bError = true
		end if
	end if
end if


Function IsEmailValid(strEmailAddr) 
  
    Dim strArray 
    Dim strItem 
    Dim i 
    Dim c 
    Dim blnIsItValid 
  
    ' assume the email address is correct  
    blnIsItValid = True 
    
    ' split the email address in two parts: name@domain.ext 
    strArray = Split(strEmailAddr, "@") 
  
    ' if there are more or less than two parts  
    If UBound(strArray) <> 1 Then 
        blnIsItValid = False 
        IsEmailValid = blnIsItValid 
        Exit Function 
    End If 
  
    ' check each part 
    For Each strItem In strArray 
        ' no part can be void 
        If Len(strItem) <= 0 Then 
            blnIsItValid = False 
            IsEmailValid = blnIsItValid 
            Exit Function 
        End If 
        
        ' check each character of the part 
        ' only following "abcdefghijklmnopqrstuvwxyz_-." 
        ' characters and the ten digits are allowed 
        For i = 1 To Len(strItem) 
               c = LCase(Mid(strItem, i, 1)) 
               ' if there is an illegal character in the part 
               If InStr("abcdefghijklmnopqrstuvwxyz_-.", c) <= 0 And Not IsNumeric(c) Then 
                   blnIsItValid = False 
                   IsEmailValid = blnIsItValid 
                   Exit Function 
               End If 
        Next 
   
      ' the first and the last character in the part cannot be . (dot) 
        If Left(strItem, 1) = "." Or Right(strItem, 1) = "." Then 
           blnIsItValid = False 
           IsEmailValid = blnIsItValid 
           Exit Function 
        End If 
    Next 
  
    ' the second part (domain.ext) must contain a . (dot) 
    If InStr(strArray(1), ".") <= 0 Then 
        blnIsItValid = False 
        IsEmailValid = blnIsItValid 
        Exit Function 
    End If 
  
    ' check the length oh the extension  
    i = Len(strArray(1)) - InStrRev(strArray(1), ".") 
    ' the length of the extension can be only 2, 3, or 4 
    ' to cover the new "info" extension 
    If i <> 2 And i <> 3 And i <> 4 Then 
        blnIsItValid = False 
        IsEmailValid = blnIsItValid 
        Exit Function 
    End If 

    ' after . (dot) cannot follow a . (dot) 
    If InStr(strEmailAddr, "..") > 0 Then 
        blnIsItValid = False 
        IsEmailValid = blnIsItValid 
        Exit Function 
    End If 
  
    ' finally it's OK  
    IsEmailValid = blnIsItValid 
    
 End Function 

%>

<form method="POST" action="Form_validation.asp" name="frmRegister">

<table width="400" align="center" border="2" cellpadding="2" cellspacing="2" bordercolor="#3366ee">
<tr><td align="center">
	<table width="100%" align="center" border="0" cellpadding="0" cellspacing="5">
	<tr><td colspan="2">&nbsp;</td></tr>
	<tr><td colspan="2" align="center">
		<%
		if len(strErrMsg) > 0 then
			Response.Write( replace(ErrMsg_CenterScreen, "%1", strErrMsg ) )
		end if
		%>                
	</td></tr>
	<tr>
		<td align="right" width="25%" valign="middle" class="<%=strNameClass%>">
			<font face="Verdana" size="1">Name&nbsp;</font>
		</td>
		<td class="clsNormal">
			<input type="text" name="Name" size="35" maxlength="50" value="<%=strName%>" class="clsNormal">
			<sup>·See below</sup>
		</td>
	</tr>
	<tr>
		<td align="right" width="25%" valign="middle" class="<%=strEmailAddrClass%>">
			<font face="Verdana" size="1">Email Address&nbsp;</font>
		</td>
		<td class="clsNormal">
			<input type="text" name="strEmailAddr" size="35" maxlength="60" value="<%=strEmailAddr%>" class="clsNormal">
			<sup>·See below</sup>
		</td>
	</tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	<tr class="clsNormal"><td colspan="2">
		<ul>
		<li>Name: ( 3 char minimum - maximum 50 characters )
		<li>EmailAddr: ( maximum 60 characters )
		</ul>
	</td></tr>
	<tr style="font-face: Verdana; font-size: 8pt;"><td colspan="2" align="center">
		<INPUT type="Submit" id="Register" name="Register" value="Click Here to Submit"
		    style="width: 200px; height: 35px; 
		    background: #999999; border: #ffce31 outset 3px; 
		    font-family: Georgia; font-size: 10pt; font-weight: bold;
		    filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr='#3366ee', EndColorStr='#ffffff');">
	</td></tr>
	</table>
</td></tr>
</table>

</BODY>
</HTML>
 
Thank you both for the great posts. they were both helpful and point me in the right direction.

This could be a helpful FAQ for some others, as it was for me!

Gary

 
bhuninghake,

In your example (i have it working for me now) how do submit information, once deemed valid, to another asp file that will write it to my DB?

Gary

 
Gary,

Once validated simply use an sql insert or what you used earlier the addNew. Here is some code that may work for you...not a function; which is obviously better, but an elseif ladder to capture any condition the user submits. Also, in my test database I included a last and first name field. Reason being it's MUCH simpler to query by name this way if needed for a report for example...or a count.

Code:
<!-- #INCLUDE FILE = "adovbs.inc" -->

<% 
  ' put this code in your DataStore.inc file
  ' you may want to make it a DataStore.asp instead 

Set objConn = Server.CreateObject("ADODB.Connection")
Set objRS = Server.CreateObject("ADODB.Recordset")
FilePath = Server.MapPath("db/users.mdb")
objConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & ";" 
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <meta HTTP-EQUIV="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>

<%
' dim variables like you did

      lname = Request.Form("lname")
      fname = Request.Form("fname")
      email = Request.Form("email")
      submit = Request.Form("submit")

' check any condition user may throw at you
' after submitting form

If submit <> "" AND lname = "" AND fname = "" AND email = "" Then
  	lnameError = "<font color=""red"">*</font>"
        fnameError = "<font color=""red"">*</font>"
 	emailError = "<font color=""red"">*</font>"
        strErrorMessage = "Last name, first name, and email address are required"

  ElseIf submit <> "" AND lname <> "" AND fname = "" AND email = "" Then
  	fnameError = "<font color=""red"">*</font>"
 	emailError = "<font color=""red"">*</font>"
        strErrorMessage = "First name and email address is required"

  ElseIf submit <> "" AND lname <> "" AND fname <> "" AND email = "" Then
  	emailError = "<font color=""red"">*</font>"
        strErrorMessage = "Email address is required"

  ElseIf submit <> "" AND lname = "" AND fname <> "" AND email <> "" Then
  	lnameError = "<font color=""red"">*</font>"
 	strErrorMessage = "Last name is required"

  ElseIf submit <> "" AND lname <> "" AND fname <> "" AND email = "" Then
  	emailError = "<font color=""red"">*</font>"
        strErrorMessage = "Email address is required"

  ElseIf submit <> "" AND lname <> "" AND fname = "" AND email <> "" Then
  	fnameError = "<font color=""red"">*</font>"
 	strErrorMessage = "First name is required"

  ElseIf submit <> "" AND lname = "" AND fname <> "" AND email = "" Then
  	lnameError = "<font color=""red"">*</font>"
 	emailError = "<font color=""red"">*</font>"
        strErrorMessage = "Last name and email address is required"

  ElseIf submit <> "" AND lname = "" AND fname = "" AND email <> "" Then
  	lnameError = "<font color=""red"">*</font>"
 	fnameError = "<font color=""red"">*</font>"
        strErrorMessage = "First and last names are required"

objRS.Close
      	Set objRS = Nothing
  
' if no errors then procede to add data to db     
Else    
      	strSQL ="SELECT UserID, LastName, FirstName, Email FROM tblUsers;"

      	objRS.Open strSQL, objConn, 3,3

         
    
      	objRS.AddNew
        objRS("LastName") = lname
        objRS("FirstName") = fname
      	objRS("Email") = email        
      	
      	objRS.Update

       ' here i get the userid (PKEY) to ensure
       ' i get the record that was just entered

        userid = objRS("UserID") 

        objRS.Update

objRS.Close
      	
' since i have the records id just entered i can
' now use a where clause to select the exact record
' and spit out the info to the user

strSQL ="SELECT UserID, LastName, FirstName, Email FROM tblUsers WHERE UserID =" & userid & ";"

objRS.Open strSQL

id =  userid
dataEntry = "<p>The following information has been sent to the database:</p>" & vbCrlf & _
                "<hr>" & vbCrlf & _
                "Name: " & objRS("FirstName") & " " & objRS("LastName") & "<br>" & vbCrlf & _
                "Email Address: " & objRS("Email")

' clear the form values 
    lname = ""
    fname = ""
    email = ""  
     
     End If

objRS.Close
%>

<!-- use a value for the forms postback.
     unlike .Net, asp does not have this feature
     so you assign a var to it...lets the user 
     not have to retype entries after submitting -->

<form action="users.asp" method="post">
 Last Name: <input name="lname" value="<%=lname%>"><%=lnameError%> 
 First Name: <input name="fname" value="<%=fname%>"><%=fnameError%>
 Email: <input name="email" value="<%=email%>"><%=emailError%> 
  <input type="submit" name="submit" value="Submit">
</form>


<!-- if error then show err else data was submitted
     using the primary key for record just inserted
     and show that to user -->
<p><%=strErrorMessage%></p>
<p><%=dataEntry%></p>

Hope this helps

Brian







 
oooops...objRS.Close
Set objRS = Nothing

needs to be within else statement...right before end if
LINE 115
sorry...caught it after i posted

-Brian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top