Javascript form validation - comments please

V

Vigil

But to have a small repeating bg static like that, that has the bonus
of sending the viewer's (my) CPU into overdrive... what's the point?
 
S

Stephen Poley

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?).

I didn't know that. Thanks.
if (!document.getElementById){
// getElementById cannot be used.
}
- should be sufficient, and avoid any language version issues.
Agreed.

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))

My feeling is that if an error can only be triggered by an *authoring*
mistake (such as mistyping an id) then it's probably better to let it
trigger a Javascript error which tells the author where to look, rather
than have it do nothing and leave one scratching ones head.
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
}

True, but I prefer to avoid expressions that complicated (eight
operators of four kinds) where reasonably possible.
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.

That's worth knowing for future reference, but in this case I feel that
the repeated tests are so simple that the performance gain is unlikely
to be worth while.

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.

I didn't realise that hadn't been standardised. Thanks. Using 'this' is
probably clearer anyway.

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?".

True - a slightly misguided attempt at humour.

Thank you again for your help.
 
S

Stephen Poley

|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.

That would explain a problem I had in the early stages, which I
addressed by substituting a non-breaking space for an empty string in
the msg function. I've got both methods in now, as a spot of
belt-and-braces.
 
S

Stephen Poley

JRS: In article <[email protected]>, seen in
W3's free TIDY said :

line 9 column 5 - Warning: inserting "type" attribute for <link> element

Bit redundant, as the stylesheet is not specific to any particular media
type.
line 101 column 1 - Warning: <table> lacks "summary" attribute
Added.

line 180 column 1 - Warning: trimming empty <p>

There is no said:
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

Incorrect, as pointed out by Nick.
The page currently lacks, AFAICS in MSIE 4 : Author name, date of
editing, links to homepage.

Links are (and were) present. Date added. I don't bother to put my name
on every page - maybe I could.
I entered xx in the first box; it thought a bit, and remarked "Line 66
Char 3 'undefined' is undefined"

This will be one of the points Richard raised. I didn't realise that
undefined was undefined (!) in the first few versions of Javascript.
(Line 66 does not hold script).

Yes said:
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.

I think it reasonable to assume that the user understands that 'send'
will not do a great deal when offline.
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.

Interesting point. I think however that it is reasonable to expect that
anyone viewing HTML source should have an editor/viewer capable of
coping with longer lines. The script is already mostly less than 72
characters wide, with those lines which are longer being longer for a
reason.

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.

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

I decided to deliberately ignore this comment. said:
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" ... .

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

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

Well, your code is certainly impressively brief. But I feel mine is
easier to understand, and also more flexible for e.g. putting up
warnings when an input is likely to be incorrect but is not definitely
so. Compactness is not as important as it used to be, with faster modems
and HTTP data-compression. Maybe still important for mobile connections
using 9.6 Kbps, but I'm not sure how many of those devices support
Javascript anyway.
IIRC, someone posted an implementation of getElementById for older
browsers in c.l.j a while ago. Yes, ...

Thanks, but on the whole I'd prefer to stick to standard Javascript
except where it's necessary to support a very widely used browser (i.e.
IE 5/6)

I've put up a new version of the page.
 
S

Stephen Poley

Why does that background have to be static?

It doesn't *have* to be, but I prefer the appearance of the scrolling
that way, especially when I have my window set to a large size.
Is it just me that is sent
into CPU overwork when a static bg is used?

I've had one person complain about that before; it turned out he was
running Netscape 7 / Mozilla (I forget which) on a machine slower than
the recommended minimum hardware configuration. What is your
configuration?
 
T

Toby A Inkster

Stephen said:
Bit redundant, as the stylesheet is not specific to any particular media
type.

@type isn't used for media types. For a CSS stylesheet, @type should be
set to "text/css".

@media is used for media types.
 
R

Richard Cornford

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.

The tests in question do seem to centre around whether the user will be
able to see[1] the error messages generated, and if not there isn't much
point in attempting the validation. So some additional checking to
ensure that error message reporting function really is modifying the
browser DOM does seem like a good idea.

[1] Sight, of course, brings us back to the problems of reporting
validation errors on screen readers that we kicked about a bit a couple
of months back.

Richard.
 
R

Richard Cornford

My feeling is that if an error can only be triggered by an
*authoring* mistake (such as mistyping an id) then it's probably
better to let it trigger a Javascript error which tells the
author where to look, rather than have it do nothing and leave
one scratching ones head.

Fair enough. In addition to authoring mistakes there is the (very)
slight possibility of the actions of a content re-writing/inserting
proxy modifying either the JS code or the ID attribute in passing, but
it would be insane to configure a proxy to do that so it would be
reasonable to argued that anyone who does so deserves what they would
get as a result.
True, but I prefer to avoid expressions that complicated
(eight operators of four kinds) where reasonably possible.

That is probably a matter of perception, I don't see the expression as
complex while I do see the multiple (in excess of two) return statements
as ugly. But you are in a better position to judge when perceived
complexity becomes a maintenance burden with your own code.

That's worth knowing for future reference, but in this
case I feel that the repeated tests are so simple that
the performance gain is unlikely to be worth while.

Yes, a script that is triggered in response to user actions like this
would have to be very poor before performance gains became a worthwhile
consideration. Personally, I like the degrade - don't degrade decision
to (where practical) be final, but that is just a matter of style. And I
would have been as likely to approach the problem form the other end and
only assigned the event handling functions with JavaScript after
confirming browser support for the features required by those functions.

Thank you again for your help.

You are welcome, and I generally applaud the intention of your page as
there is little that I consider more stupid than taking the intrinsic
reliability of the combination of HTML forms and server-side scripting
and making it dependent on client-side scripting (or worse, browser
specific client-side scripting). I remain undecided about some aspects
of the problem (mostly related to the behaviour of speech browsers and
especially screen readers) but I doubt that I would be able to move
towards drawing definite conclusions without more public debate on the
subject in general.

Richard.
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
Toby A Inkster <UseTheAddressInMySig@deadspam
..com> posted at Mon, 8 Dec 2003 07:35:20 :-
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.


But the distribution does not include the manual; hence, the small file
should also refer to obtaining the manual.
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
On Fri, 5 Dec 2003 23:38:13 +0000, Dr John Stockton


Links are (and were) present. Date added. I don't bother to put my name
on every page - maybe I could.

AFAICS in IE4, where "see" does not include reading the source.


I think it reasonable to assume that the user understands that 'send'
will not do a great deal when offline.

Certainly; but it could be useful, since Send merely transmits something
to be ignored, to provide a means whereby a user can play with it when
off-line without generating unnecessary errors.
Interesting point. I think however that it is reasonable to expect that
anyone viewing HTML source should have an editor/viewer capable of
coping with longer lines. The script is already mostly less than 72
characters wide, with those lines which are longer being longer for a
reason.

I only have 72-character eyeballs; and, if one may be citing line
number, it's nice to be sure that it is the same number as the author
sees. But it all depends on what tools the author uses. Editing with
PFE, I can pack a paragraph rapidly. Granted, it's hard to avoid all
long lines.

Well, your code is certainly impressively brief. But I feel mine is
easier to understand, and also more flexible for e.g. putting up
warnings when an input is likely to be incorrect but is not definitely
so. Compactness is not as important as it used to be, with faster modems
and HTTP data-compression. Maybe still important for mobile connections
using 9.6 Kbps, but I'm not sure how many of those devices support
Javascript anyway.

There is also the point that, in larger forms, the author does not have
to handle great lengths of repetitive stuff.

I'd not thought of warnings. As is, the object that defines a line has
two entries that do testing; optional entries for tests with different
responses could be added. Certainly, it is intended as a demonstration
to be adapted for actual use, and I've just added words to that effect.
 
S

Stephen Poley

@type isn't used for media types. For a CSS stylesheet, @type should be
set to "text/css".

@media is used for media types.

Hmm ... I think we both had our brains idling here. The issue is the
type attribute of the link element. I managed to completely misread the
relevant bit of the HTML spec; you appear to be thinking of a different
spec entirely. '@type'?

What I would have said if my brain had been in gear at the time
(assuming it now is):

Bit redundant, as the type of the stylesheet is primarily defined by the
HTTP headers (at least, I have heard this claimed often enough that I'm
inclined to believe it - must study the RFCs myself one day). Presumably
this attribute only saves browsers from retrieving stylesheets they
don't understand, and I don't think there are any web-browsers in the
wild which handle stylesheets but not CSS - are there?
 
V

Vigil

Hmm. I am using Opera 7.23 on an Athlon XP 2something. I have also checked
with the Mozillas and MSIE in WinXP (same machine). Always the CPU load
goes up. Try running a CPU load monitor and yours should too.
Alternatively, make a test page without the static bg and put them side by
side, scroll each and you might notice the static bg page is slightly less
smooth (depending on your CPU, of course). I've heard it reported that it
does it on all browsers.
 
T

Tux

I want to produce a form for competition entry which would need minimal
editing from year to year. Since the entrants to the competition would have
to have birthdates between certain limits I would want to calculate these
and add the results to a selection list, something like

<select>
<option>Under-10 (born 1994 to 1996</option>
<option>Under-12 (born 1992 or 1993</option>

etc.

where the option values would include some javascript, e.g.

<option>Under-10
<script type="text/javascript">
document.write(" (born " + u10Lower + " to " + u10Upper + ")");
</script>
</option>

I have limited access to server side scripting, hence the reason for doing
it on the client side.

However, scripting seems to be illegal within an <option> tag. Does anyone
have any idea how I could do this?
 
P

Philipp Lenssen

Tux said:
I have limited access to server side scripting, hence the reason for
doing it on the client side.

However, scripting seems to be illegal within an <option> tag. Does
anyone have any idea how I could do this?

I suggest creating the page offline then and uploading it completely (a
static, non-JavaScript version). You shouldn't use JavaScript just
because you don't have access to a server-side language, really. If you
do it offline, you can use a variety of languages, e.g. Win-ASP by
installing IIS on the localhost.
 
T

Toby A Inkster

Stephen said:
I don't think there are any web-browsers in the
wild which handle stylesheets but not CSS - are there?

No, but there are browsers that handle non-CSS style sheets (e.g. XSLT in
MSIE and Mozilla; JSSS in NN4)
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
Toby A Inkster <UseTheAddressInMySig@deadspam
..com> posted at Tue, 9 Dec 2003 07:35:06 :-
Mine did.

If you got a version that will run at a Win98 DOS prompt, what was the
URL you got it from?
 
S

Stephen Poley

I don't like innerHTML for a different reason... that is it could be
read-only or whatever,

Perhaps you could explain a bit. Under what circumstances would that
arise?
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.

I'd be happy to bin innerHTML completely, but I understand that it's the
best available with IE - unless you know different?
 
S

Stephen Poley

Nice! But why still apply js when the server side testing is so complete?

I do try to explain that on the page.
IMO the form should :
- use cookies to prevent people have to fill in all the fields again next
time

Could be appropriate in some cases, but OTOH some forms tend only to get
filled in once. And of course quite a lot of people have cookies
disabled. A bit out of the scope of this article.
- send a copy of the mail to the sender (I hate to make copies myself or not
knowing later what exactly I submitted)

Good point, but not an appropriate feature of the form itself - that
would need to be done by the server script. (And one would of course
need anti-spammer precautions).
 

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
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top