473,325 Members | 2,785 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

form validation design setup

Rik
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 undoable (or at least not desireable), to add all kinds
of events directly in the HTML code directly, certainly since there's a lot
of duplication in validation. Since I'm not that experienced in using
javascript, I wonder what you think about the following plan before I
start:

When generating the form, I can add classnames to the
input(/textarea/select), and add checks on that, for instance, I've got:

<input class="major validateAlpha" type="text">
<input class="minor validateAlphaNonEmpty some_other_class" type="text">
<input class="highlighted validateAlphaNonEmpty remoteUsername">
<input class="small validateChecked" type="checkbox">

Input types are stored in a database (that's how I determined what classes
to give to the inputs), and a dynamic js is called in the header, with a
Validation object:
var Validation = {
'Alpha':{
'property':'value',
'type':'regex'
'value':'/^[a-z]*$/i',
'msg':'Only letters a-z.'
}
'AlphaNonEmpty':{
'property':'value',
'type':'regex'
'value':'/^[a-z]+$/i',
'msg':'Only letters a-z, must not be empty.'
}
'Checked':{
'property':'checked',
'type':'compare'
'value':true,
'msg':'Must be checked.'
}
}

Now, on the onload event of the window, a function is fired. This function
adds a function to the submit event of the form. This function will loop
through to form elements, checking for className matching
/\bvalidate([a-z]*)\b/i. If it matches, the previous captured validation
name is taken from the Validation object, and this gives:
1. What property to check (value, selectedIndex, checked etc.)
2. What kind of comparison has to be done (check the value directly or use
a Regex)
3. What is should be compared/matched to.
4. What message should be given to help the user to correct his possible
error.

When one or several of the fields are 'invalid', the submitting is
cancelled, and the user is given hints on what to change. Possibly adding
an 'error' classname which will give it a red border or a red label or
something, maybe tip on what kind of data should be in there. Also a
removal of the effect after a revalidation on the onchange event seems
desirable (element.className = element.className.replace('/\berror\b/','').
If everything's valid, offcourse let the submitting go on.

I also got a 'remote...' classname, which on checking should use a
XMLHTTPRequest, with the capture in /\bremote([a-z]*)\b/ as GET variable to
the server, which will respond with an object:
{
'valid': false,//or true offcourse
'msg':'Username is already taken.'
}
This object is checked on wether this is a valid value, and a possible
error message is displayed, submitting is stopped.(If the request fails,
let it submit and let the server figure it out offcourse.)

Quick question in between: if I answer with such an JSON object, must I use
eval() the ResponseText, or is there a better way?

That's about the core of the plan. I really want to write most of this from
scratch for learning purposes, but before such an undertaking I want to
make sure I'm on the right track.

So:
- I'll be using a lot of JSON, is this supported by all/most major browsers
like this?
- Is using classnames like this a good idea. If not, why, and how can I
assign a certain validation to a field?
- Is the suggested flow a logical one?
- Is there something major missing/wrong?
- Is it perhaps better to validate each element on the onchange event also,
or not?

All remarks and suggestions welcome, and thanks in advance,
--
Rik Wasmus
Oct 25 '06 #1
11 2946
Hi Rik,
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).
I'm in a very similar situation and was working on this just a few
nights ago.

Now, offcourse it's undoable (or at least not desireable), to add all kinds
of events directly in the HTML code directly, certainly since there's a lot
of duplication in validation. Since I'm not that experienced in using
javascript, I wonder what you think about the following plan before I
start:
I think this is a very interesting idea.

<snip about how the checking is done>

I don't know if I could use this class name method as I have to use
some less than routine validations.

When one or several of the fields are 'invalid', the submitting is
cancelled, and the user is given hints on what to change. Possibly adding
an 'error' classname which will give it a red border or a red label or
something, maybe tip on what kind of data should be in there. Also a
removal of the effect after a revalidation on the onchange event seems
desirable (element.className = element.className.replace('/\berror\b/','').
If everything's valid, offcourse let the submitting go on.
I do want a uniform way to show these errors. I put together a little
of what I am thinking of using. This might help you with the last part
of your problem.

<URL
http://peter.michaux.ca/examples/form-validation/form-validation-example.html>

To do this indication in a uniform way for many different pages with
different form layouts, the big tricks are not messing up the form
layout with little error messages for each field and showing reasonable
indicators around each field.

I decided the Ruby on Rails way of grouping the error messages at the
top of the form and then outlining the problem fields with red would be
good.

Outlining the error fields is difficult because the browsers are not
compatible. Some form elements can have outlines in some browsers.

In my example the red border on a multiple select in Safari doesn't
look good but it does make some indication. I haven't ever used a
multiple select and Safari isn't so common anyway.

I used navigator.userAgent to determine which browser the script is
running in and style the elements according to what works for that
browser if it needs non-default behavior. I tested in IE, Firefox,
Safair and Opera. Using navigator.userAgent is considered a sin around
comp.lang.javascript and for good reason. However I think here it might
be justified. In the uncommon situation where a browser is not
identifying itself as expected with navigator.userAgent the red border
may not appear or may look a little different then I intended because
the incorrectly used red indication doesn't work on that browser. This
is not critical because the grouped error message will still appear at
the top of the form. With browser I didn't test there is a good chance
that the default red indicators don't work some of the time also. This
isn't such a big concern for me because that group message will be at
the top and those browsers are not common anyway. I could change so I'm
not using navigator.userAgent for browser detection but then these
other browser may still not show the red indicators properly. The
grouped message is my important part and the red outlines are a bonus
if they work.

The other way I thought about doing this was to lay the page out with
the error indicators already in the markup but without them showing
red. Then if an error occurs just add a classname to the indicator to
make it go red. This could be done with inline error messages as well
instead of the grouped message I am using. This is complicated by the
fact that more than one message may need to be shown for a particular
field and the space for the messages must be available. Eventhough this
method could potentially show similar red errors for all browsers, the
reason I didn't choose this method is because the markup will take much
more time for each page, I'm not always going to be doing the markup so
someone might mess this up, and the browsers that don't work with the
example above are a small percentage (probably far smaller than the
percentage of browsers without JavaScript).

Someone here is going to bark about my choices.

I also got a 'remote...' classname, which on checking should use a
XMLHTTPRequest, with the capture in /\bremote([a-z]*)\b/ as GET variable to
the server, which will respond with an object:
{
'valid': false,//or true offcourse
'msg':'Username is already taken.'
}
This object is checked on wether this is a valid value, and a possible
error message is displayed, submitting is stopped.(If the request fails,
let it submit and let the server figure it out offcourse.)
Probably a good idea to lump all the remote validations into just one
request to the server.

Quick question in between: if I answer with such an JSON object, must I use
eval() the ResponseText, or is there a better way?
If you know the JSON is safe then I think there is no problem using
eval. However there is a parser for JSON in JavaScript

<URL http://www.json.org/js.html>

This parser modifies some built in JavaScript objects' prototypes. That
means you probably want to modify this parser so it doesn't break your
other code. There are only a few lines near the bottom to change how
you will call the methods you will call.

That's about the core of the plan. I really want to write most of this from
scratch for learning purposes, but before such an undertaking I want to
make sure I'm on the right track.

So:
- I'll be using a lot of JSON, is this supported by all/most major browsers
like this?
As far as I know all browsers since many years ago will work. For the
JSON eval method, the browser needs to support object and array
literals and eval().
- Is using classnames like this a good idea. If not, why, and how can I
assign a certain validation to a field?
If the JavaScript library needed to use this technique is small then it
might be great.
- Is the suggested flow a logical one?
- Is there something major missing/wrong?
What happens when you need some special custom validation? Say two
fields that depend on each other like a start and end date. You will
want to be able to write some custom JavaScript that will check that
the end date comes after the start date. How can you work this into
your class name scheme?
- Is it perhaps better to validate each element on the onchange event also,
or not?
I would find validation onchange a bit annoying because that is not
what I'm used to when I use web pages. Someone else may have a good
reason why using onchange would work well.

Peter

Oct 25 '06 #2
ASM
Rik a écrit :
When one or several of the fields are 'invalid', the submitting is
cancelled, and the user is given hints on what to change. Possibly adding
an 'error' classname which will give it a red border or a red label or
something,
Because, on error, you certainly send user on wrong filled field
document.theForm.thatElement.focus();
Except with IE you don't need to add an 'error' class,
css do it by them self
input:focus, input.error { border: 2px solid red; background: yellow }

if(ie) document.theForm.thatElement.className += 'error';

or have a function to give events to fields it is IE

function errorIE() {
var f = document.myForm;
for(var i=0; i<f.length; i++) {
f[i].onfocus = function() { this.className='error'; }
f[i].onblur = function() { this.className=''; }
}
}
onload = function() { if(ie) errorIE(); }

the server, which will respond with an object:
{
'valid': false,//or true offcourse
'msg':'Username is already taken.'
}
with such an JSON object, must I use
eval() the ResponseText, or is there a better way?
if it is a JS 'object' where is the problem ?

if (http_request.status == 200) {
var content = http_request.responseText;
if(content.valid) {
document.getElementById('answer').innerHTML = content.msg;
document.theForm.Username.value='';
document.theForm.Username.focus();
}
}
with only sending back message or nothing would have been enough

if (http_request.status == 200) {
var content = http_request.responseText;
if(content.length>0) {
content =+ 'This '+document.theForm.Username.value+' ';
document.getElementById('Username').innerHTML = content;
document.theForm.Username.value='';
document.theForm.Username.focus();
}
}

Nick Name : <input name="Username" ... >
<span id="Username"></span>
- Is using classnames like this a good idea.
I find that very clever !
(un peu compliqué mais astucieux)
how can I
assign a certain validation to a field?
It seems form elements's accepted attributes are :
name, id, value, events, class, disabled
(and for some : checked or selected)
But I think you can add via JS what you want as attributes,
like the tag could be an object (in sens tag = new Object() )
- Is it perhaps better to validate each element on the onchange event also,
or not?
It could be ! ! :-)

No, most important is : messages must be very very very clear.

--
ASM
Oct 25 '06 #3
ASM
Peter Michaux a écrit :
Outlining the error fields is difficult because the browsers are not
compatible. Some form elements can have outlines in some browsers.
I prefer give help to visitor and to work step by step on
pre-validation, that's to say the loop on fields stops if there is an
error, then focus is given to this wrong field.
Given focus, automatically field appearance changes
(by css way or if IE by events 'onfocus' 'onblur')
is not critical because the grouped error message will still appear at
the top of the form.
Hu ?
- I have to climb up to see why the form doesn't submit ?
- I have to run up and down between messages and fields ?

With a stopping loop you can easily display right message on right place.

this.parentNode.getElementsByTagName('span')[0].innerHTML = mesg;

<p><input ...><span></span></p>

or :

#myForm p span { display: none; }
#myForm p.msg span { display: block }
#myForm .red { border: 2px solid red; background: yellow; }

if document.myForm[i] is something wrong
{
document.myForm[i].parentNode.className = 'msg';
document.myForm[i].className = 'red';
}

<p><input ...><span>Wrong url</span></p>

The other way I thought about doing this was to lay the page out with
the error indicators already in the markup but without them showing
red. Then if an error occurs just add a classname to the indicator to
make it go red.
just what I said ;-) but display or visibility are much better

This could be done with inline error messages as well
instead of the grouped message I am using.
ffftt : ekzacktely what I think and did say :-(

This is complicated by the
fact that more than one message may need to be shown for a particular
field and the space for the messages must be available.
why available space ?
if message is in a block (natural or relative)
on display = 'block'
the alerting block pushes others ones

..
Oct 25 '06 #4
Rik wrote:

[snip]
Now, offcourse it's undoable (or at least not desireable), to add all
kinds of events directly in the HTML code directly, certainly since
there's a lot of duplication in validation. Since I'm not that
experienced in using javascript, I wonder what you think about the
following plan before I start:

When generating the form, I can add classnames to the
input(/textarea/select), and add checks on that, for instance, I've
got:

<input class="major validateAlpha" type="text">
If your aim is to remove extraneous material from the markup, I don't
see how that is much different from doing what you're arguing against.
It might save some typing, but in either case, the attribute values of
the element still includes content that isn't directly related to the
document structure.

Instead, why don't you place this information in the script itself? For
example, an array of objects where each control has its own element
containing the necessary information to validate said control.
Alternatively, an object that references other objects: the name of the
control is the property name within the object. In either case, one need
only loop through the elements collection of the form. If a control
doesn't need to be validated directly (it's handled as part of some
other check, for instance) then the property can be left undefined.
Elisions can achieve the same thing within array literals.

The means of validation are likely to be either a function or a regular
expression. For the former, a reference to the element (or the
collection for radio buttons and checkboxes) can be passed as the
argument; for the latter, the value of the value property for that
control (regular expressions are of most use with textarea and input
elements). A reference to either sort of object can be stored under the
same property name, and either a typeof operator check or comparing the
constructor property of the object against the Function or RegExp
constructor functions can be used to determine how to handle either one.
If additional parameters are necessary when calling a function (for
example, boundaries in a range check), they can also be stored as an
object within the array.

Dr Stockton presents a scheme such as this in his discussion of form
validation[1].
... className matching /\bvalidate([a-z]*)\b/i.
Keep in mind that some characters that constitute word breaks are legal
class names. The hyphen, for instance. A more tolerant assertion would
be the beginning and end of input, or whitespace:

/(^|\s)validate([a-z]*)(\s|$)/i
If it matches, the previous captured validation name is taken from
the Validation object, and this gives:
1. What property to check (value, selectedIndex, checked etc.)
If functions are used to check the element, this will be implied. The
type of validation applied to a select element wouldn't be suitable for
a textarea, for instance.
2. What kind of comparison has to be done (check the value directly
or use a Regex)
Again, this would be implied.
3. What is should be compared/matched to.
And again.

[snip]
I also got a 'remote...' classname, which on checking should use a
XMLHTTPRequest, ...
You should think carefully whether that would be worth the effort. After
all, one needn't return the entire form should certain values be
unacceptable. More to the point, why make the user wait for two (or
more) HTTP transactions? Client-side validation is supposed to reduce
network traffic and provide near-instant feedback. Unless frequent
failure is anticipated, then I would think that the effort of returning
a smaller form would be justified.
... which will respond with an object:
{
'valid': false,//or true offcourse
'msg':'Username is already taken.'
}
An alternative would be to use response codes to signify success or
failure. The 2xx series all denote success, and 204 No Content can be
used where no additional information needs to be sent to the client. 409
Conflict would seem to be reasonable in the case of an error, as is 404
as a general error response.

[snip]
Quick question in between: if I answer with such an JSON object, must
I use eval() the ResponseText, or is there a better way?
If the response is always trustworthy, then eval is fine.

[snip]
- I'll be using a lot of JSON, is this supported by all/most major
browsers like this?
If they implement XMLHttpRequest, then they'll also support the JSON
syntax, which is simply a restricted subset of ECMAScript. Douglas
Crockford touches on this in JSON in JavaScript[2], and there will be
discussions in the group archive.
- Is using classnames like this a good idea. If not, why, and how can
I assign a certain validation to a field?
I would say no, mainly because it's not relevant to the markup and only
to a script. As such, I would argue for placing the data in the script
in the first place.

[snip]

Mike
[1] <http://www.merlyn.demon.co.uk/js-valid.htm#VFF>
[2] <http://www.json.org/js.html>
Oct 25 '06 #5
Rik
Michael Winter wrote:
Rik wrote:

[snip]
>Now, offcourse it's undoable (or at least not desireable), to add all
kinds of events directly in the HTML code directly, certainly since
there's a lot of duplication in validation. Since I'm not that
experienced in using javascript, I wonder what you think about the
following plan before I start:

When generating the form, I can add classnames to the
input(/textarea/select), and add checks on that, for instance, I've
got:

<input class="major validateAlpha" type="text">

If your aim is to remove extraneous material from the markup, I don't
see how that is much different from doing what you're arguing against.
It might save some typing, but in either case, the attribute values of
the element still includes content that isn't directly related to the
document structure.
Arguable. I have:
a: limited amounts valid attributes offcourse.
b: I expect a lot of repetition of valid 'types'.
c: giving a classname to an input element that describes it's valid content
had a lot to do with the document IMHO.
Instead, why don't you place this information in the script itself?
For example, an array of objects where each control has its own
element containing the necessary information to validate said control.
The nature of the desired application is so, that over a hundred elements
may exist, with a lot of repetition I like to avoid. Also, filling out one
form, may result in the appearance of a previously unexisting subform,
which would require loading the types of that elements etc. It would mean a
lot more overhead I think. It would also require the server to make a
response with both the form/nodes to add, and the items to add to the
validation array, essentially duplicating the traffic.
Alternatively, an object that references other objects: the name of
the control is the property name within the object. In either case,
one need only loop through the elements collection of the form. If a
control doesn't need to be validated directly (it's handled as part
of some other check, for instance) then the property can be left
undefined. Elisions can achieve the same thing within array literals.
Well, I could try a database-join-like construction:
var Validation = {
'element_name1':'Alpha',
'element_name2':'AlphaLowerNonEmpty',
}
var Valids = {
'Alpha' : '/^[a-z]*$/i',
'AlphaLowerNonEmpty' : '/^[a-z]+$/',
'Checked': 'checked'
}
In the current version, if there's no classname 'valid....', there would no
checking be required, so 'any content goes'. That's the same thing you mean
by 'the property can be left undefined'?
The means of validation are likely to be either a function or a
regular expression. For the former, a reference to the element (or the
collection for radio buttons and checkboxes) can be passed as the
argument; for the latter, the value of the value property for that
control (regular expressions are of most use with textarea and input
elements). A reference to either sort of object can be stored under
the same property name, and either a typeof operator check or
comparing the constructor property of the object against the Function
or RegExp constructor functions can be used to determine how to
handle either one. If additional parameters are necessary when
calling a function (for example, boundaries in a range check), they
can also be stored as an object within the array.
You're right there's in the original post an unneccary overhead in naming
the property to check, this can indeed be determined by the type of
element.
Dr Stockton presents a scheme such as this in his discussion of form
validation[1].
I'll check out the url.
>... className matching /\bvalidate([a-z]*)\b/i.

Keep in mind that some characters that constitute word breaks are
legal class names. The hyphen, for instance. A more tolerant
assertion would be the beginning and end of input, or whitespace:

/(^|\s)validate([a-z]*)(\s|$)/i
Good point.
[snip] (type of action can indeed be determined by type of element)
>I also got a 'remote...' classname, which on checking should use a
XMLHTTPRequest, ...

You should think carefully whether that would be worth the effort.
After all, one needn't return the entire form should certain values be
unacceptable. More to the point, why make the user wait for two (or
more) HTTP transactions? Client-side validation is supposed to reduce
network traffic and provide near-instant feedback. Unless frequent
failure is anticipated, then I would think that the effort of
returning a smaller form would be justified.
The 'remote' will indeed be very rare, and offcourse, like you say, I've
got a fallback when javascript does not work/a certain check is not done by
javascript, which will give back a smaller form.
>... which will respond with an object:
{
'valid': false,//or true offcourse
'msg':'Username is already taken.'
}

An alternative would be to use response codes to signify success or
failure. The 2xx series all denote success, and 204 No Content can be
used where no additional information needs to be sent to the client.
409 Conflict would seem to be reasonable in the case of an error, as
is 404 as a general error response.
Well, could be done like that, but using headers as a indication of failure
doesn't sit right with me for some reason. Offcourse, this would simplify
the response, as a failure is determined from the header, and the reason
(usermessage) can be determined from the responseText. However, I can image
a request fails for another reason (safety settings of the user for
instance), so I really want a HTTP header other then 200 to be taken as
'remote validation failed, just go on submitting and let the server figure
it out'. Allthough a 204 or a 409 seem highly unlikely returns because of
user settings.
>Quick question in between: if I answer with such an JSON object, must
I use eval() the ResponseText, or is there a better way?

If the response is always trustworthy, then eval is fine.
Check.
>- I'll be using a lot of JSON, is this supported by all/most major
browsers like this?

If they implement XMLHttpRequest, then they'll also support the JSON
syntax, which is simply a restricted subset of ECMAScript. Douglas
Crockford touches on this in JSON in JavaScript[2], and there will be
discussions in the group archive.
I'll check it out.
>- Is using classnames like this a good idea. If not, why, and how can
I assign a certain validation to a field?

I would say no, mainly because it's not relevant to the markup and
only to a script. As such, I would argue for placing the data in the
script in the first place.
Well, it says something about the type of data it holds, so it's debatable
in my opinion. Much in the same way you could have 'normal' anchors in a
page, and a classed 'readmore' anchor with a different style, I don't think
deriving information about a form-element by classname is such a bad idea.
Classnames aren't only for css...

Well, I seem very much on the defence on this, but that's only because I
want to make sure of any implication this design would bring with it ;)
--
Rik Wasmus
Oct 25 '06 #6
Rik
ASM wrote:
Rik a écrit :
>When one or several of the fields are 'invalid', the submitting is
cancelled, and the user is given hints on what to change. Possibly
adding an 'error' classname which will give it a red border or a red
label or something,

Because, on error, you certainly send user on wrong filled field
document.theForm.thatElement.focus();
Except with IE you don't need to add an 'error' class,
css do it by them self
input:focus, input.error { border: 2px solid red; background:
yellow }
Well, several elements can be invalid, so 'focus' is not the right choice
here I think (allthough setting focus will offcourse happen). Also, on the
initial filling out of the form this may seem weird, a red border on
inputting the first data...
>the server, which will respond with an object:
{
'valid': false,//or true offcourse
'msg':'Username is already taken.'
}
>with such an JSON object, must I use
eval() the ResponseText, or is there a better way?

if it is a JS 'object' where is the problem ?

if (http_request.status == 200) {
var content = http_request.responseText;
Would that not make a string containing the literal response? I doubt it
will be an object with accessable properties.....
with only sending back message or nothing would have been enough

if (http_request.status == 200) {
var content = http_request.responseText;
if(content.length>0) {
content =+ 'This '+document.theForm.Username.value+' ';
document.getElementById('Username').innerHTML = content;
document.theForm.Username.value='';
document.theForm.Username.focus();
}
}
You're right in that an empty response might be considered 'valid &
continue'. However, it does not sit right with me for some reason.
Nick Name : <input name="Username" ... >
<span id="Username"></span>
I would certainly opt for an insertBefore() method rather than having tons
of empty elements in the form, which will most likely rarely be used.
Keeping the HTML clean :-).
>- Is using classnames like this a good idea.

I find that very clever !
(un peu compliqué mais astucieux)
Well thank you, but not everyone seems to agree, I'll seriously have to
consider all implications.
>- Is it perhaps better to validate each element on the onchange
event also, or not?

It could be ! ! :-)
Well, major problem is offcourse 'skipping', when a user fills out a field,
skips ahead with the idea to return later, error messages could be quite
annoying. In any case, the onblur is definitely not the right choice, I'll
have to think about the onchange..
--
Rik Wasmus
Oct 25 '06 #7
Rik
ASM wrote:
>is not critical because the grouped error message will still appear
at the top of the form.

Hu ?
- I have to climb up to see why the form doesn't submit ?
- I have to run up and down between messages and fields ?

With a stopping loop you can easily display right message on right
place.

this.parentNode.getElementsByTagName('span')[0].innerHTML = mesg;

<p><input ...><span></span></p>

or :

#myForm p span { display: none; }
#myForm p.msg span { display: block }
#myForm .red { border: 2px solid red; background: yellow; }

if document.myForm[i] is something wrong
{
document.myForm[i].parentNode.className = 'msg';
document.myForm[i].className = 'red';
}

<p><input ...><span>Wrong url</span></p>
Well, that would mean empty, useless elements for every input field.
I'd say a:
node = document.forms[0].elements[0]
errorspan= document.createElement('span');
errorspan.setAttribute('class','error');
text = document.createTextNode('This is the error message.');
errorspan.appendChild(text);
node.parentNode.insertBefore(errorspan,node);
>The other way I thought about doing this was to lay the page out with
the error indicators already in the markup but without them showing
red. Then if an error occurs just add a classname to the indicator to
make it go red.

just what I said ;-) but display or visibility are much better
Not having an error message at all when it's valid trumps display/visibiliy
IMHO :-).
--
Rik Wasmus
Oct 25 '06 #8
ASM wrote:
Peter Michaux a écrit :
Outlining the error fields is difficult because the browsers are not
compatible. Some form elements can have outlines in some browsers.

I prefer give help to visitor and to work step by step on
pre-validation, that's to say the loop on fields stops if there is an
error, then focus is given to this wrong field.
If the validation of the entire form is being done when the user
presseses the submit button then I think it is better to show all
errors in the form fields. Showing one at a time would annoy me because
I would think "Why didn't it tell me that before!?!" I would end up
clicking submit, then fixing a mistake, clicking submit, fixing,
clicking, fixing etc as I learn about each mistake.

Hu ?
- I have to climb up to see why the form doesn't submit ?
The page automatically scrolls to the error message when it popups up.
So no you don't have to climb up.

- I have to run up and down between messages and fields ?
If the form was long then yes you would have to scroll the screen. The
red boxes on the inputs and the original label on the field will
usually give the necessary information to tell the user what needs
fixing.

With a stopping loop you can easily display right message on right place.

this.parentNode.getElementsByTagName('span')[0].innerHTML = mesg;

<p><input ...><span></span></p>
This isn't a general purpose approach because there might be other
spans in the parentNode.

I think it would be better to create and insert the span when necessary
and remove it when it is not necessary.
or :

#myForm p span { display: none; }
#myForm p.msg span { display: block }
#myForm .red { border: 2px solid red; background: yellow; }
This won't work will all types of form elements in all types of
browsers. At the very least, see radio and check boxes in Firefox and
Safari and select in Safari. They don't get the red border or the
yellow background. Different indicators need to be used in different
browsers to either work or look good.

if document.myForm[i] is something wrong
{
document.myForm[i].parentNode.className = 'msg';
document.myForm[i].className = 'red';
}

<p><input ...><span>Wrong url</span></p>

The other way I thought about doing this was to lay the page out with
the error indicators already in the markup but without them showing
red. Then if an error occurs just add a classname to the indicator to
make it go red.

just what I said ;-) but display or visibility are much better

This could be done with inline error messages as well
instead of the grouped message I am using.

ffftt : ekzacktely what I think and did say :-(
fffftt ?
This is complicated by the
fact that more than one message may need to be shown for a particular
field and the space for the messages must be available.

why available space ?
if message is in a block (natural or relative)
on display = 'block'
the alerting block pushes others ones
This block element may mess up the form layout in many cases.

Peter

Oct 25 '06 #9
I also got a 'remote...' classname, which on checking should use a
XMLHTTPRequest, with the capture in /\bremote([a-z]*)\b/ as GET variable to
the server, which will respond with an object:
{
'valid': false,//or true offcourse
'msg':'Username is already taken.'
}
This object is checked on wether this is a valid value, and a possible
error message is displayed, submitting is stopped.(If the request fails,
let it submit and let the server figure it out offcourse.)

Probably a good idea to lump all the remote validations into just one
request to the server.
On second thought, I think this use of AJAX is not necessary. The
server has to be capable of validating this form completely if
JavaScript is off and for security. This level of validation can
indicate the errors you would be checking with AJAJX. This saves
downloading an AJAX library to the client just for form validation.
Like you said in another post this situation would probably be rare
anyway so the any extra time involved would be less important.

Peter

Oct 25 '06 #10
Rik wrote:
Michael Winter wrote:
>Rik wrote:
[snip]
>><input class="major validateAlpha" type="text">

If your aim is to remove extraneous material from the markup, I
don't see how that is much different from doing what you're arguing
against. It might save some typing, but in either case, the
attribute values of the element still includes content that isn't
directly related to the document structure.

Arguable.
Perhaps, but you asked for opinions, and I gave you mine. :-)
I have:
a: limited amounts valid attributes offcourse.
I'm arguing for an approach that requires no attributes aside from the
fundamental (type, name, etc.).
b: I expect a lot of repetition of valid 'types'.
Just as you might designate controls to use the same validation type:

<input name="username" class="validateAlpha" value="">
<input name="last-name" class="validateAlpha" vlaue="">

the same thing can be achieved by referencing the same functions or
regular expressions:

var validationData = {
username: { test: isAlpha, ... },
'last-name': { test: isAlpha, ... },
...
};

where isAlpha is a function that expects an object reference as its only
argument.
c: giving a classname to an input element that describes it's valid
content had a lot to do with the document IMHO.
You're describing behaviour: how a control should be validated.
>Instead, why don't you place this information in the script itself?
For example, an array of objects where each control has its own
element containing the necessary information to validate said
control.

The nature of the desired application is so, that over a hundred
elements may exist, with a lot of repetition I like to avoid.
Done.
Also, filling out one form, may result in the appearance of a
previously unexisting subform, which would require loading the types
of that elements etc.
So? The data might instead be structured so that the id or name of the
form refers to the relevant information for that form:

var validationData = {
myForm: { ... },
subForm: { ... }
};

Alternatively, the data can be entirely separate.
It would mean a lot more overhead I think. It would also require the
server to make a response with both the form/nodes to add, and the
items to add to the validation array, essentially duplicating the
traffic.
You would still be doing that, albeit in a different format.

[snip]
>If a control doesn't need to be validated directly (it's handled as part
of some other check, for instance) then the property can be left
undefined.
[snip]
In the current version, if there's no classname 'valid....', there
would no checking be required, so 'any content goes'. That's the same
thing you mean by 'the property can be left undefined'?
Yes. You would attempt to lookup the property value:

var data = validationData[control.name];

if (data) {
/* Use the properties of the object
* to validate the control.
*/
}

If the property isn't defined the variable, data, will have the value
undefined and the condition will evaluate to false.

[snip]

[Using HTTP status codes to indicate success]
However, I can image a request fails for another reason (safety
settings of the user for instance), ...
The server determines the reply. If the request failed due to security
settings (restricting ActiveX, cross-domain request), the request
wouldn't be sent in the first place - the script would raise an exception.

[snip]

Mike
Oct 25 '06 #11
Rik
Michael Winter wrote:
>>><input class="major validateAlpha" type="text">

If your aim is to remove extraneous material from the markup, I
don't see how that is much different from doing what you're arguing
against. It might save some typing, but in either case, the
attribute values of the element still includes content that isn't
directly related to the document structure.

Arguable.

Perhaps, but you asked for opinions, and I gave you mine. :-)
Don't get me wrong, I appreciate it very much!

I did not post to this expecting confirmation I was right, but a good
discussion about merits, which is often the way to a well informed
decision.
>I have:
a: limited amounts valid attributes offcourse.

I'm arguing for an approach that requires no attributes aside from the
fundamental (type, name, etc.).
True.
>b: I expect a lot of repetition of valid 'types'.

Just as you might designate controls to use the same validation type:

<input name="username" class="validateAlpha" value="">
<input name="last-name" class="validateAlpha" vlaue="">

the same thing can be achieved by referencing the same functions or
regular expressions:

var validationData = {
username: { test: isAlpha, ... },
'last-name': { test: isAlpha, ... },
...
};

where isAlpha is a function that expects an object reference as its
only argument.
Well yes, but there are a lot of types of alpha-input (requires to be not
empty or not, only lowercase/uppercase, can have numbers, etc...).

I don't want to give a function name here, allthough the idea to give one
simple string to compare is a good thing. I think indeed I can determine
the type of comparison from the element type, and have just function to
either compare a regex (text-inputs/textarea's), a ckecked property, etc.
>c: giving a classname to an input element that describes it's valid
content had a lot to do with the document IMHO.

You're describing behaviour: how a control should be validated.
And in a lot of classes for html elements, it describes how a element
should be rendered. In my opinion that's equal to what content a form
element should hold.

To absolutely come clean:
- I do not want inline javscript, all script should be included by a url.
- All forms are built with pretty complex code (well, complex, complex for
me ;) ), so it's a hard thing to add all form element names/id's into a
different, callable, javascript.
- I already have a list of different 'types' of date (around 25), to which
all fields abide. That's stored in the database, and easily loadable as
JSON Validation object. Building a seperate js file, that will keep track
of the last form requested, and the names/id's of the forms, will be a big
pain, or a major overhead when I just dump out all possible names/ids and
checkstrings for the entire interface (hmmmz, caching of this on the user
side might hold some merit). That's the primary reason I'd rather use
classnames ;).
>>Instead, why don't you place this information in the script itself?
For example, an array of objects where each control has its own
element containing the necessary information to validate said
control.

The nature of the desired application is so, that over a hundred
elements may exist, with a lot of repetition I like to avoid.

Done.
Well, very slight data to receive overhead (stringlength JSON object -
(stringlenght classname + avarage occurance)) =in favor of classname, if
we want to compare byte by byte. But then again, less code required/run on
client side.
>Also, filling out one form, may result in the appearance of a
previously unexisting subform, which would require loading the types
of that elements etc.

So? The data might instead be structured so that the id or name of the
form refers to the relevant information for that form:

var validationData = {
myForm: { ... },
subForm: { ... }
};

Alternatively, the data can be entirely separate.
Hard to maintain in the current setup.

On an very different, yet related subject: If I have set the validationData
to the variables required for myForm, and later on, I wish to add the
variables for subForm, can I do this with JSON? If yes, how to add? If no,
what's the alternative?
>In the current version, if there's no classname 'valid....', there
would no checking be required, so 'any content goes'. That's the same
thing you mean by 'the property can be left undefined'?

Yes. You would attempt to lookup the property value:

var data = validationData[control.name];

if (data) {
/* Use the properties of the object
* to validate the control.
*/
}

If the property isn't defined the variable, data, will have the value
undefined and the condition will evaluate to false.
You're right, the check wether is should be validated, and how, will indeed
procude a slightly more busy js (I have honestly no idea how good js is
with regexes, anybody done a test in different browser/different regex
compications yet?).
[Using HTTP status codes to indicate success]
>However, I can image a request fails for another reason (safety
settings of the user for instance), ...

The server determines the reply. If the request failed due to security
settings (restricting ActiveX, cross-domain request), the request
wouldn't be sent in the first place - the script would raise an
exception.

Good to know.

Once again: I really appreciate the input!
--
Rik Wasmus
Oct 26 '06 #12

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

Similar topics

3
by: wk6pack | last post by:
Hi, How do you check for a empty value from a form? lservice = request.form("pservice") if not isnull(lservice) then <== this doesnt work. tried "" empty string and it still didnt work....
2
by: iam247 | last post by:
Hi I have an ASP form which only includes an option list. The list is dynamically created but includes a default value, which is an instruction "Select a group". The code is shown at bottom....
2
by: Barbara Alderton | last post by:
I setup some standard Required Field Validation controls and one Custom validation control on an ASP.NET page (within a user control) to validate text entry. I also setup a Summary Control to post...
2
by: Mark Sandfox | last post by:
I have a tricky control validation issue. I have probably designed this the wrong way but here is what I have. I have 6 TextBoxes; tbPN, tbA, tbC, tbS, tbZ, tbDOB and there are 20 of each with...
2
by: Adrian | last post by:
Hi everyone I have a web form where the validation works pefectly I copied the file, renamed it, and all of a sudden the validation stopped working(on the copied form). I have two panels on...
45
by: Pat | last post by:
its seems asp.net validation doesn't fire when using FireFox? Tested a page and it doesn't fire. It seems the javascript doesn't fire Any ideas?
4
by: Greg Scharlemann | last post by:
I'm trying to setup a dyamic dropdown list that displays a number of text fields based on the selected number in the dropdown. The problem I am running into is capturing the data already entered...
10
by: gweasel | last post by:
What is the best way to apply a Validation Rule - or rather, where is the best place to put it? Is there an advantage to putting it on the field in the table vs setting the validation rule on the...
7
by: sharsy | last post by:
Hi guys, I would like to setup a validation rule for a database in microsoft access that restricts data entry so that a certain field can only be filled in if another field has a specific answer...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.