Dealing with Blank Fields - Page 3
September 5, 2000
The most commonly used and simple need for validation is to ensure that
your site visitors do not leave a crucial form-field blank. You could use
client-side scripting to prevent this, but not all users will have
the right type of browser or JavaScript support enabled. So, to make sure
no one slips through the cracks, it is time to use some server-side
scripting to accomplish this task. For this example, let us assume that
you have a form with First Name, Last Name, Social Security Number, Address,
City, State, Zip Code, Telephone Number and Email Address - like this
one (feel free to use the source code for this standard form on your
own pages):
Next, assume that none of the fields can be left blank when submitted.
The best thing for you as a developer to do, is to write a small block of
code that will check each form-field sequentially. We will accomplish
this task with a For...Each loop inside our conditional test
that makes sure the form has been submitted. Note:
For...Each loops are used in VBScript and ASP to sequentially
iterate, or move through, each item in a collection.
<%
const numFields = 9
dim errorArray()
redim preserve errorArray(numFields)
if Request.Form("isSubmitted") then
...
...
ErrorMsg = ""
x = 0
For Each formField in Request.Form
if Len(Request.Form(formField)) = 0 OR Request.Form(formField)
= "noneSelected" then
errorArray(x) = True
ErrorMsg = ErrorMsg & Ucase(formField) & "<br>"
else
errorArray(x) = False
end if
x = x + 1
Next
%>
Note that in the example above we've line-wrapped the
code at the equals symbol (=), but in reality the command is one
long line.
You are probably thinking that was a pretty big mouthful for such a small
request, so let's take a look at what this little block of code does,
line by line.
const numFields = 9 is a constant that we set equal to the
number of fields in the form we are validating. Using constants is a
good practice because if you ever re-use this code elsewhere you can keep
everything the same, change the constant, and validate as many fields as
necessary.
dim errorrArray() sets up, or declares, an array named
"errorArray," whose length is not defined. We will be using this array
to store the names of the form-fields that return errors so that they
can be referenced later to provide meaningful error messages to your users.
The next line, redim preserve errorArray(x), redefines the
size of the array to match the current value of numFields. Remember, this
array is where errors are being stored, so it is important that it matches
the number of form elements in the collection. The little extra bit of
code, preserve, basically makes sure that the array is kept
active in memory throughout the rest of the code.
if Request.Form("isSubmitted") then is there only to show you
where this code block of code is going in relation to our conditional
statement that checks to see if the form is submitted. The two ellipses
(...) indicate whatever code you may already have there, like the code
that stores the values of the form-fields in variables.
ErrorMsg = "" and x = 0 both initialize
variables (ErrorMsg and x, respectively) with a default value of an empty
string for ErrorMsg and 0 for x. ErrorMsg is a string that will be used
to store an HTML-formatted message displayed on the page when a validation
error occurs (more on this later). X is being used as a type of counter
that will start at 0 and continue to increase until the
For...Each loop is concluded. It will be used to reference
specific locations within the array, errorArray.
For Each formField in Request.Form is a special version of a
For...Next loop called a For...Each loop that
sequences through a collection, in this case our form. On each iteration of
the loop, formField will be equal the name of the current
form-field in the collection. For example, if the loop is on Zip Code,
formField will equal "zip_code" and the this
Request.Form(formField) code will return the value of
zip_code. Pretty convenient, no?
if Len(Request.Form(formField)) = 0 Request.Form(formField) =
"noneSelected" then is a simple conditional statement that asks
"If the current form-field has no length (is empty) or is 'noneSelected"
for the state field, then do the following..."
errorArray(x) = True and ErrorMsg = ErrorMsg &
Ucase(formField) & "<br>" are executed when the previous
if statement is found to be "True" or when the value of the current
form-field is empty. Thus, the current element of errorArray is set to
"True" to denote an error and the ErrorMsg string is set to
equal itself (in case this is not the first error) and then adds the name
of the form-field that is incorrect.
If the form-field does have a length, or is not empty, then the
current element in the errorArray is set to "False" since there is no error
to report.
x = x + 1 increments x every time each time the code loops.
Okay, if you have followed that successfully, (if not,
email me and I'll help if I can)
the next step is to provide some notice to the site visitor that they have
submitted an error. This step is actually very easy, we simply add a
small conditional test right underneath the body tag
(or wherever you want):
...
<body>
<% if ErrorMsg <> "" then %>
<font color="red" size="3"><b>
<%= ErrorMsg %>
</font><br>
<% end if %>
<form name="sample1" method="post">
...
All this code does is ask: "If the ErrorMsg variable is not
empty, then there is an error message to tell the user, so I will output
it in big red bold text." If there is no value in
ErrorMsg then the output is ignored and the form is returned
as usual. At this point, you are probably asking what that silly array was
for, and now I will tell you. Have you ever seen the forms where the name
of the field that was left blank is a different color or bold? We are
going to recreate that effect using this array.
If you think this part is going to be hard to do, don't, it is not. All
that needs to be done is not unlike what you already did to retain the
value for the state field. Before each "caption" for the input fields,
you simply need to put, in ascending order (from 0...n) a check
to see if the corresponding value of the array is true or not. The
following code will show you exactly what to do if that is not clear:
<tr>
<td><% if errorArray(0) = "True" then %>
<font color="red"><b>
<% end if %>First Name: <% if errorArray(0) = "True" then %>
</b></font>
<% end if %>
</td>
<td>
<input name="first_name"
size="25"
maxlength="50"
value="<%= first_name %>">
</td>
</tr>
<tr>
<td>
<% if errorArray(1) = "True" then %>
<font color="red"><b>
<% end if %>Last Name: <% if errorArray(1) = "True" then %>
</b></font>
<% end if %>
</td>
<td>
<input name="last_name"
size="25"
maxlength="50"
value="<%= last_name %>">
</td>
</tr>
|
WARNING:
In writing this article, I believe I discovered some type of bug
or oddity about the ASP compiler. Every form element will be read
in sequentially, as they are coded. However, for whatever reason,
this particular page grabs City before Last Name. I asked around,
and no one is certain why. So, a word of caution to you,
although errorArray(1) should be for Last Name, it is
actually City, and errorArray(2) is Last Name. Needless to say,
if you encounter problems, experiment a bit to see what order the
form elements are being processed.
|
NOTE:
The second check of the array after the caption is
actually to put in the closing tags for font and
bold. However, these really are not necessary.
One of the neat things about tables is that, in most browsers,
the ending </td> actually ends any formatting within
that cell. However, the WDVL believes in compliant code and so,
if you want to be correct, close the tags. If not, omit at your
own discretion and risk.
|
If you would like to see this in action, I have set up a
demo on Enfused.com. Please note that I added the code to my form so
that it has short-term memory of what the user submits.
Once you have played around a bit and tried this stuff yourself (which I
might add is the only true way to learn), move on to the next page and we
will talk about validating specific fields.
Even Smarter Forms - Page 2
Using ASP for Form Handling: Part 2 - Server Side Form-Field Validation
Making Sure People Do Not Enter L33t As Their Name - Page 4
|