Javascript form validation - comments please

P

Philipp Lenssen

Stephen said:
On 5 Dec 2003 09:17:26 GMT, "Philipp Lenssen" <[email protected]>
wrote:

stored >once, or else you would implement validation on the client
and on the >server (and you would need to change two things for every
change).

Yes, you do end up with some duplication. It's a question of how much
you feel is worth investing to help the user. The point of the page
(perhaps I should review whether it comes over) is not so much that
you should use client-side validation, but that if you do so, do it
properly.

You don't necessarily end up with duplication; e.g. you could store the
patterns, mandatory fields, default-values etc. inside XML on the
server and create the JavaScript code dynamically.
On Windows, you could even use JScript in ASP to have parts of the same
code sit around on the server and the client.
As for the benefits: it depends. With a broadband connection and a
fast server there probably isn't much benefit. Sometimes however one
has to wait 10-20 seconds for a server response. With a more complex
form and/or a not-so-careful user, needing 2 or 3 bites at the
cherry, it could save the user quite a bit of time.

I usually find response times of say 1 to 2 seconds OK. Of course when
it would take 20 seconds for a server response that's bad. But let's
say the validation is complex, then you _must_ do it on the server.
Imagine you want the user to enter his street adress and city and you
want to validate if that's a real street by comparing with your server
database. To do the same validation on the client would mean writing a
lot of code and send the data to the client. This might take much
longer than 20 seconds to download! (Besides, you might not want to
share the data.)
And then you have to do it all again on the server-side because you
don't know if the user has JavaScript!
 
M

m

I have quite often (as have probably many of you) come across HTML forms
with irritating bits of Javascript attached. The last straw on this
particular camel's back was a large form I was asked to complete in
connection with attendance at a seminar. After spending more than 15
minutes on it, I clicked on the submit button - and nothing happened.

Looking round the pages on Javascript form validation that Google
produced for me (well, 15-20 of them!), none seemed to emphasise the
points that I feel to be important. And some even advocated bad
practices. So I decided to stick my neck out and produce a page on how
it ought to be done:

http://www.xs4all.nl/~sbpoley/webmatters/formval.html

I would be interested in comments, suggested improvements etc. In
particular any cross-browser Javascript aspects I have overlooked.
(I've tried the page in Opera 7, Mozilla 1.1, IE 6, NN4).


In the alerts, consider adding a
message that you can't use the enter-key to move
between fields. Or, perhaps, this should be done at least
on the first couple of fields' alerts.
Without an explanation, a novice can get confused.
 
S

Stephen Poley

The most common alternative (and more precise) term for "object
detection" is "feature detection" as it takes into account that some of
the things that need detecting are not necessarily objects but may get
down to ECMA Script implementation details.

The assumption that the existence of the document.getElementById method
can be used to infer that the browser has full dynamic display
capabilities falls down in the face of, for example, Opera 5 & 6 and Web
Browser 2 (on the Palm OS (based on NetFront)) which both implement the
method but do not implement either of the required interfaces. (Opera 6
puts up a JavaScript error message and Web Browser 2 just fails
quietly).
A feature/object detecting script would have gone to the effort of
verifying the existence of the required dynamic interfaces before
attempting to use them. Not that knowing that an element has a text node
as its firstChild necessarily means that writing to the nodeValue
property of its firstChild will result in changes in the display, but at
least knowing that the firstChild property is a reference to an object
prevents the attempt to write to one of its properties from putting up a
JavaScript error report.

<snip>

OK you have a good point here - though you make it in a rather
roundabout fashion - that I've missed a trick or two on the
feature/object detection front. (It's not a feature-inference script,
it's a defective feature-detecting script. ;-P )

I've added a couple of tests to the commonCheck routine. I'd be grateful
if you could give it a quick look and see if there's anything else I've
missed.
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
http://www.xs4all.nl/~sbpoley/webmatters/formval.html

I would be interested in comments, suggested improvements etc.


W3's free TIDY said :

line 9 column 5 - Warning: inserting "type" attribute for <link> element
line 101 column 1 - Warning: <table> lacks "summary" attribute
line 180 column 1 - Warning: trimming empty <p>
line 104 column 9 - Warning: Attribute "size" not supported in HTML 4.01
line 111 column 9 - Warning: Attribute "size" not supported in HTML 4.01
line 118 column 9 - Warning: Attribute "size" not supported in HTML 4.01
line 125 column 9 - Warning: Attribute "size" not supported in HTML 4.01
Info: Doctype given is "-//W3C//DTD HTML 4.01//EN"
Info: Document content looks like HTML 4.01 Transitional
7 warnings, 0 errors were found!

....


I do not like patterned backgrounds; but yours is not too bad.

The page currently lacks, AFAICS in MSIE 4 : Author name, date of
editing, links to homepage.

I entered xx in the first box; it thought a bit, and remarked "Line 66
Char 3 'undefined' is undefined" (Line 66 does not hold script). This
appears to be all that it will do, except that the Send button also
tries to contact your Web site - without success, as I am offline. You
could add, apart from the ostensible form, a control to adapt behaviour
for off-line use.

You invite source viewing. Since you do not know what it will be viewed
with, ISTM that both HTML and script should be formatted for a
72-character right margin.

I would change the NOSCRIPT to acknowledge that enabling may be
impossible - ... "disabled" -> "not enabled" & "If you can enable it
...." is perhaps adequate but not ideal.

The ostensible wording is good; there is a split infinitive in
formval.js <g>.

I think formval.js Line 66 is :
if (document.getElementById == undefined)

Should that be "'undefined'"? I like using "var U" to define an
undefined variable ... but you could put "var undefined" ... .

By using proceed instead of continu you could obviate a comment.

Your actual validity-testing could be shortened by using the approach of
my js-valid.htm .

IIRC, someone posted an implementation of getElementById for older
browsers in c.l.j a while ago. Yes, ...

news:comp.lang.javascript said:
if(document.all && !document.getElementById) {
document.getElementById = function(id) {
return document.all[id];
}
}
 
R

Richard Cornford

I've added a couple of tests to the commonCheck routine.
I'd be grateful if you could give it a quick look and see
if there's anything else I've missed.

From the commonCheck function:-

|if (document.getElementById == undefined)
| return true; // older browser - leave validation to the server
|var elem = document.getElementById(ifld);
|if (!elem.firstChild && !elem.innerHTML)
| return true; // older browser

The first thing that struck me about this was the comparison with -
undefined - in the first test. undefined was introduced with JavaScript
1.3 but didn't make it into JScript until 5.0 (or maybe 5.5?). Which
makes me think that it probably should not be used in a test that is
intended to allow the script to degrade cleanly on older browsers, IE 4,
for example, will produce an (unhelpful) "undefined is undefined" error.
There are techniques that render undefined safe to use in any
environment, such as:-

window.undefined = window.undefined;

- or -

this.undefined = this.undefined; //executed in a global context.

- but they are probably not necessary as a type-converting test:-

if (!document.getElementById){
// getElementById cannot be used.
}

- should be sufficient, and avoid any language version issues.

The value returned from the call to getElementById and assigned to the
local variable - elem - is not checked. Because you know that you have
put an element into the document with a corresponding ID attribute it
seems reasonable to assume that the function call will return a
reference to that element. But it doesn't cost much to double check, and
if the element was not returned you can be guaranteed that the message
writing function will not work. So:-

if (!elem || (!elem.firstChild && !elem.innerHTML))

It would also be possible to combine the two tests into one - if -
statement:-

var elem;
if(!document.getElementById ||
((!(elem = document.getElementById(ifld)) ||
(!elem.firstChild && !elem.innerHTML)))){
return true; // leave validation to the server
}

It is worth baring in mind that this is a test to avoid executing the
script on browsers that cannot support it, some of these will be "older
browsers" but others will the latest versions of non-dynamic browsers
such as some of those found on small PDAs and cell phones.

As it stands this test will be executed upon every change made to a
field in the form. If the browser fails on the first attempt it will
also fail on all subsequent attempts so it might be worth ensuring that
the test is not needlessly repeated once it has failed. I notice that
the - commonCheck - function is expecting to have a reference to the
invoking form element passed to it as its - vfld - parameter. As a
result, having identified an unsupporting browser, the onchange handler
for the corresponding form field could be permanently disabled by
assigning null to its onchnge property:-

vfld.onchange = null; //future change events will
//not be calling JavaScript.

(knocking onsubmit out from the FORM element is also an option).

Other alternatives might include replacing the - commonCheck - function
with another that did nothing but return true, short-circuiting all
subsequent testing.

Looking at the ONCHANGE attributes in your HTML to verify the origin of
the - vfld - parameter I notice that you are using an unreliable
accessor to pass the reference to the form element:-

| <INPUT TYPE=text NAME="telnr"
| ID="telnr" SIZE="35" MAXLENGTH="25"
| ONCHANGE="validateTelnr(telnr, 'inf_telnr', true);">

The identifier - telnr - is being used to pass the reference to INPUT
element to the - validateTelnr - function. Many browsers provide the
functions generated with event handling attribute strings with custom
scope handling mechanisms that will resolve the identifier - telnr - as
a named property of the form, others provide named form elements as
named properties of the global object so scope resolution will find the
right object under the name - telnr - at the end of the scope chain.
Unfortunately, these behaviours are non-standardised and inconsistently
implemented, there are also browsers that will do neither and - telnr -
will remain undefined.

However, the JavaScript language requires that when a function is
invoked as a method of an object the - this - keyword is always a
reference to that object, and event handling functions are always
invoked as methods of the element with which they are associated. That
means that event handling attribute code can always refer to the element
to which it is attached with the - this - keyword and so pass on
references to that element, while side-stepping the inconsistencies in
scope resolution from (internally generated) event handling functions:-

ONCHANGE="validateTelnr( this, 'inf_telnr', true);">

Nothing else stands out as potentially problematic, though I don't think
that you should be commenting on people managing to survive for more
than 100 years, I would put the cut-off point at around 125. Anyone who
has made it past 100 is unlikely to appreciate the comment "Getting on a
bit, aren't you?".

Richard.
 
R

Richard Cornford

|if (!elem.firstChild && !elem.innerHTML)

I forgot to mention that the innerHTML test may not be the best as empty
strings type-convert to boolean false, so - !elem.innerHTML - will be
true if the innerHTML string exists but is empty. That is not a problem
with your original HTML page as none of the relevant elements are
initially empty but generally a test for the lack of support for
innerHTML might be best done with - (typeof elem.innerHTML !=
"string") - as that relationship is unaffected by the content of the
innerHTML string (if it exists). This might be relevant to your code as
some of the functions are setting innerHTML to an empty string.

Richard.
 
N

Nick Kew

one of infinite monkeys said:
W3's free TIDY said :

What version of Tidy? It looks rather old and it's made some bad mistakes.
line 9 column 5 - Warning: inserting "type" attribute for <link> element
Correct - provided it got the right type.
line 101 column 1 - Warning: <table> lacks "summary" attribute
Yes - though a low-priority warning (required only for AAA compliance)
line 180 column 1 - Warning: trimming empty <p>
Fair enough but not necessary.
line 104 column 9 - Warning: Attribute "size" not supported in HTML 4.01
That is seriously screwed - I'm surprised!
Info: Doctype given is "-//W3C//DTD HTML 4.01//EN" Correct.

Info: Document content looks like HTML 4.01 Transitional
Nonsense. That's a known Tidy bug from pre-sourceforge days;
I thought it had been dealt with.
 
S

Stephen Poley

I usually find response times of say 1 to 2 seconds OK.

Agreed. If you can provide a 2 second response via a 33K modem (or
thereabouts), then client-side validation is redundant.
Of course when
it would take 20 seconds for a server response that's bad. But let's
say the validation is complex, then you _must_ do it on the server.
Imagine you want the user to enter his street adress and city and you
want to validate if that's a real street by comparing with your server
database. To do the same validation on the client would mean writing a
lot of code and send the data to the client. This might take much
longer than 20 seconds to download!

No argument from me there - indeed I make a comment on the page roughly
to that effect. But you might help the user by doing a quick client-side
check that a street name has indeed been filled in, and that it looks at
least a bit like a street name (rather than, say, just a house number).
 
S

Stephen Poley

Looking round the pages on Javascript form validation that Google
produced for me (well, 15-20 of them!), none seemed to emphasise the
points that I feel to be important. And some even advocated bad
practices. So I decided to stick my neck out and produce a page on how
it ought to be done:

http://www.xs4all.nl/~sbpoley/webmatters/formval.html

I would be interested in comments, suggested improvements etc. In
particular any cross-browser Javascript aspects I have overlooked.


Thank you to everyone for the comments, especially the very detailed
comments from Richard and Dr John. I will work my way through them and
put up an improved page in a few days time.
 
J

Jim Ley

|if (!elem.firstChild && !elem.innerHTML)

I forgot to mention that the innerHTML test may not be the best as empty
strings type-convert to boolean false, so - !elem.innerHTML - will be
true if the innerHTML string exists but is empty.

I don't like innerHTML for a different reason... that is it could be
read-only or whatever, so if you're going to test to see if changing
innerHTML works you can do it with

foo.innerHTML='<b>Chickens</b>'

if (foo.childNodes etc. or whatever non innerHTML methods you prefer
to test the existence of elements.

Jim.
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
Agreed. If you can provide a 2 second response via a 33K modem (or
thereabouts), then client-side validation is redundant.

You cannot rely on doing that. The user may acquire the form while
connected, and want to fill it up at leisure then send it when next
connected. The user may be on a train, wireless-connected, and go into
a tunnel. You may, of course, feel that an unimportant case.
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
What version of Tidy? It looks rather old and it's made some bad mistakes.

A fairly recent one, for DOS. Unlike the one I used before, it has the
flaw of not identifying its version in its normal output. It's one
where two of the four instances of "sourceforge" in the EXE is actually
spelt "sourgeforge". EXE file dated 2003/02/27-13:49:16, fetched
2003/06/20-07:42:10.

Correct - provided it got the right type.

Not correct, actually; I was using TIDY in check-only mode, so
"inserting" is not really right.

Yes - though a low-priority warning (required only for AAA compliance)

? Alcoholics Anonymous of Armenia
? Azerbaijani Automobile Association?
Probably not; but I do not recognise the initials, and I do recall being
advised that a summary should be provided by some probably-other source.
AIUI, it helps non-sighted users and similar.

Fair enough but not necessary.

That is seriously screwed - I'm surprised!

Agreed; but I use "<input size" myself, and TIDY accepts it ...
"less-than""letter" in script can confuse that Tidy; but I don't see it
present.
Nonsense. That's a known Tidy bug from pre-sourceforge days;
I thought it had been dealt with.


What, and where, is the latest TIDY for DOS? Mine is :

imports\tidy\tidy.exe -version
HTML Tidy for Windows released on 1st February 2003

A binary scan of the EXE for -version apparently finds 2 copies of the
text given by tidy -help !!
 
D

Daniel R. Tobias

rf said:
I was required to answer questions once on a computer at, of all places, a
ski rental shop in (you guessed it) the U S of A. Mammoth to be exact. This
computer insisted my postcode (they called it a zip code) had to be exactly
5 digits long. My postcode is 2154. Of course I lied.

Same form insisted my phone number must be of the form 555 555 555 (IIRC).
Mine is +61 2 5555 5555. I lied again.

And then there are the sites that refuse to accept the fact that
(e-mail address removed) is a valid e-mail address... some people still think
that top level domains are no longer than 3 letters long.
 
V

Vigil

Why does that background have to be static? Is it just me that is sent
into CPU overwork when a static bg is used? I've seen some sites have
plain monotonous colour static bgs - what's the point of that?
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
Why does that background have to be static? Is it just me that is sent
into CPU overwork when a static bg is used? I've seen some sites have
plain monotonous colour static bgs - what's the point of that?

Any background other than a plain, light-coloured one, or one scarcely
distinguishable from that, is a handicap to at least some potential
readers. Using a patterned background demonstrates that the site is
intended to be admired, rather than to be read.
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
Toby A Inkster <UseTheAddressInMySig@deadspam
..com> posted at Sun, 7 Dec 2003 11:29:13 :-
You missed out on the 2003/07/01 release by a week and a half.

Drat. The distribution site appears to be down at present.

IIRC & IMHO, there is a flaw of omission in the distribution - in what
one actually fetches. It does not, or did not, include a small text or
HTML file saying which version it is and where it comes from. This
would be a useful reminder for those thinking of updating or
recommending.
 
T

Toby A Inkster

Dr said:
IIRC & IMHO, there is a flaw of omission in the distribution - in what
one actually fetches. It does not, or did not, include a small text or
HTML file saying which version it is and where it comes from.

Running "tidy -version" will tell you which version you are using.

The manual (on Linux, "man tidy") tells you where you can download new
versions.
 
B

Bart Lateur

rf said:
Right at the bottom is the standard address fields with the <annoying> drop
down country selection </annoying>. So, having filled in the entire form I
change the country from the default USA (of course) to Australia.

Immediately a new "international" form fills my canvas, with, as you may
guess, all of the fields blank.

Whatever anybody else may think, IMO if something like a country is so
important as to it changes everything else, it shouldn't be on the same
form. Instead, it should be a choice you have to make upfront, on a
separate page.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,125
Latest member
VinayKumar Nevatia_
Top