473,782 Members | 2,534 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Form validation help

A customer wants me to convert a VB app I wrote for them into a web app
for remote users to do data entry.

So, I'm writing a small ASP program which prompts the user for data,
much like a VB program. I would like to interactively validate the data
as they are entering it, rather than waiting until they submit the
form. So, I am doing something like this (this is a very simple
example):

<head>
<script language=javasc ript>
function validatefield1( )
var i;
i = document.myForm .field1.value
if ( i < 10 or i > 20 ) {
alert("please enter a # between 10 and 20!");
document.getEle mentByID('field 1').focus();
return false;
}
return true;
}
function validatefield2( )
var i;
i = document.myForm .field2.value
if ( i < 20 or i > 30 ) {
alert("please enter a # between 20 and 30!");
document.getEle mentByID('field 2').focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form name=myForm id=myForm method=post action='/nextpage.asp'>
Field1: <input type=text size=2 id=field1 name=field1
onblur='validat efield1();'>
Field2: <input type=text size=2 id=field1 name=field1
onblur='validat efield2();'>
</form>
</body>

Here is the problem:
By default the first field has focus. If I press tab to bypass it
without entering anything, focus shifts to field2 immediately. The
onblur event fires, which checks the value in field1, sees it is
invalid, so prints an error message and resets the focus to field2.

Naturally, this causes field2 to lose focus. This causes field2's blur
event to kick of, which causes an error (since the field is blank),
printing an error, setting focus back to field2.

The effect is an endless loop of error messages.

I've tried other combinations of events, such as ondeactivate, but they
all result in the same behavior.
Why does the focus shift from field1 to field2 prior to the onblur
event completing?
Can someone explain the proper sequence of event processing on ASP
forms? When I press tab in field1, why does focus shift to field2 prior
to the onblur event for field1 completing? I can't seem to find this
documented anywhere in the msdn documentation to explain how events are
sequenced on IIS forms.
Alternatively, can someone suggest which event I would use to
accomplish what I'm trying to do? I've read the newsgroup and people's
comments about not using the onblur event, but I'd prefer to
interactively validate data, rather than waiting until the form is
submitted which I think is messy and unprofessional, compared to the VB
apps I've written. Plus the customer wants me to keep the web page
operationally identical to the VB app, and the VB app validates data at
the point of entry.
Thanks
Vin

Feb 25 '06 #1
2 1646
VK
> i = document.myForm .field1.value

This is a call for troubles, especially in IE. Better use the
conventional form addressing syntax. And always use "var" in variable
declaration. First you're avoiding global variable while you need a
local one. Secondly add <div id="i"></div> into your page for a sample
of other bad things it may lead to.

var v = document.forms['myForm'].elements['field1'].value;
if ( i < 10 or i > 20 ) {
There is not "or" operator in JavaScript. It's called "||" here.

if (v<10 || v>20) {

All together:

function validatefield1( ) {
var fld = document.forms['myForm'].elements['field1'];
var v = fld.value;
if (v<10 || v>20) {
alert('wrong input');
fld.select();
fld.focus();
}
}

By default the first field has focus. If I press tab to bypass it
without entering anything, focus shifts to field2 immediately. The
onblur event fires, which checks the value in field1, sees it is
invalid, so prints an error message and resets the focus to field2.

Naturally, this causes field2 to lose focus. This causes field2's blur
event to kick of, which causes an error (since the field is blank),
printing an error, setting focus back to field2.

The effect is an endless loop of error messages.

I've tried other combinations of events, such as ondeactivate, but they
all result in the same behavior.
Why does the focus shift from field1 to field2 prior to the onblur
event completing?


I donno - I guess the main part of errors came from "or". Overall you
have no way to guess why did user came to some field and why left it
unfilled for another field. Maybe she's using tab to navigate and she
wants to fill some underlaying fields first. Maybe she got blink in her
AIM so she needs to switch the window. Maybe she started to fill her
account info and she needs to look at another file for the last number.
It is futile tu guess and it is *highly* irritating to users to be
alert(ed) on each onblur.

I would suggest to drop this approach all together. You better put some
visual marks (say green) near each properly filled field as long as
your user navigates from field to field. And onsubmit you do one more
final check and place say red marks near all unfilled or unproperly
filled fields. Your users will just love this and its author :-)

Feb 25 '06 #2
On 25/02/2006 23:47, VK wrote:
i = document.myForm .field1.value
[...] And always use "var" in variable declaration.


The OP did. In both functions, it was the line prior to the one you
quote above.

[snip]
var v = document.forms['myForm'].elements['field1'].value;


When property names conform to the Identifier production, dot notation
will suffice:

var v = document.forms. myForm.elements .field1.value;

Better yet, avoid resolution of the control altogether:

<input name="field1" size="2" onchange="valid ateField1(this) ;">

function validateField1( control) {
var v = +control.value;

if ((v < 10) || (v > 20)) {
alert('Please enter a number between 10 and 20.');
if (control.focus)
control.focus() ;
return false;
}
return true;
}

By the way, it goes without saying that names like 'field1' are terrible.

[snip]
By default the first field has focus. If I press tab to bypass it
without entering anything, focus shifts to field2 immediately. The
onblur event fires, which checks the value in field1, sees it is
invalid, so prints an error message and resets the focus to field2.
Quite.
Naturally, this causes field2 to lose focus. This causes field2's
blur event to kick of, which causes an error (since the field is
blank), printing an error, setting focus back to field2.

The effect is an endless loop of error messages.
Which is why it's imperative to avoid the blur event when messing with
control focus. In fact, the blur event should be avoided in general for
validation purposes as warnings can become, from the user's perspective,
harassment.
I've tried other combinations of events, such as ondeactivate, but
they all result in the same behavior.
Use the change event, as illustrated above. To catch omitted fields,
also validate using the submit event.
Why does the focus shift from field1 to field2 prior to the onblur
event completing?


It doesn't. The listener for the first control does complete, but the
loss of focus during the execution of that listener queues another blur
event. When the function returns, the event is dispatched into the
document tree, calling the other listener.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Feb 26 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
3924
by: Stefan Richter | last post by:
Hi, after coding for days on stupid form validations - Like: strings (min / max length), numbers(min / max value), money(min / max value), postcodes(min / max value), telefon numbers, email adresses and so on. I thought it might be a better way to programm an automated, dynamic form validation that works for all kinds of fields, shows the necessary error messages and highlights the coresponding form fields.
6
4342
by: Charles Banas | last post by:
weird subject - i hope more than just one curious regular will hear me out. :) ok, i've got a bit of a big problem, and i need answers as soon as possible. i know this forum is meant for web developers, but is relevant discussion. i'm not OT here unless someone thinks i'm trolling (which i'm not, obviously). then i'll disappear and never show my face again. :P
4
2653
by: bnp | last post by:
Hi All, I am quite new the JavaScript. Basically I am a C++ programmer, but now I am working on JavaScript since last 5 days. I have a problem regarding the form validation. I have created a script that validates the form fields. the validation procedure is called ONCLICK event of the submit button. Follwowing is the structure of the validation procedure.
9
4180
by: julie.siebel | last post by:
Hello all! As embarrassing as it is to admit this, I've been designing db driven websites using javascript and vbscript for about 6-7 years now, and I am *horrible* at form validation. To be honest I usually hire someone to do it for me, grab predone scripts and kind of hack out the parts that I need, or just do very minimal validation (e.g. this is numeric, this is alpha-numeric, etc.)
14
2155
by: JNariss | last post by:
Hello, I am fairly new to asp and jscript and am now in the process of learning some form validation. I am taking one step at a time by validating each field and testing it before moving onto the next one to be sure I am correct. I ran into a problem with my validation when I added an else if code to my code. Here is what I tried to do: Form (ITTermination) has a field (EmployeeName) which I would like to validate to check for no...
27
4758
by: Chris | last post by:
Hi, I have a form for uploading documents and inserting the data into a mysql db. I would like to validate the form. I have tried a couple of Javascript form validation functions, but it appears that the data goes straight to the processing page, rather than the javascript seeing if data is missing and popping up an alert. I thought it may be because much of the form is populated with data from the db (lists, etc.), but when I leave...
11
3001
by: Rik | last post by:
Hello guys, now that I'm that I'm working on my first major 'open' forms (with uncontrolled users I mean, not a secure backend-interface), I'd like to add a lot of possibilities to check wether certain fields match certain criteria, and inform the user in different ways when the data is wrong (offcourse, this will be checked on posting the data again, but that's something I've got a lot of experience with). Now, offcourse it's...
5
3225
by: lucyh3h | last post by:
Hi, I am trying to use XMLHttpRequest to do server side validation. I have several fields on a form and a submit button. The submit button has an event assocated with it when clicked. The javascript method will do the form validation for each field one by one. For each field, an XMLHttpRequst will be made to a PHP file and get the return, either set an error field (<span>'s innerHTML) or leave it empty. Then I'll check the error field...
0
1338
by: karen987 | last post by:
This is an email form on an ASP page. I want to add validation before it submits, The current validation only checks "name, email, and content" (server side) if the spaces are empty. I need to add the following so that the form is not submitted unless the following is true. 1. The "name" field must be maximum 20 characters. Not left empty. Letters only. 2. The "email" must be a valid email. Not left empty. 3. The "subject" must be maximum...
3
3299
uranuskid
by: uranuskid | last post by:
Hey folks, I was going to include a contact form on my website. Well, in the first place that seemed an easy thing to do with a form that prompts a PHP file validating the input vaiables and using it's mail () function to send the mail. However, as I got more into that topic I realized that one should be really concerned about the validation part to prevent spam abuse. There are shiploads of 'mail scripts' available with each of them has...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10313
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9944
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7494
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3643
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2875
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.