473,416 Members | 1,869 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,416 software developers and data experts.

Phone Validation Problem (I reformatted the code to make it easier to read)

<script language="JavaScript" type="text/javascript">
<!--
function validate(theForm)
{
var validity = true; // assume valid
if(frmComments.name.value=='' && validity == true)
{
alert('Your full name is required. Please enter your full name!');
validity = false;
frmComments.name.focus();
event.returnValue=false;
}
if(frmComments.company.value=='' && validity == true)
{
alert('Your company name is required. Please enter the name of your
company!');
validity = false;
frmComments.company.focus();
event.returnValue=false;
}
var pattern1 = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (!pattern1.test(frmComments.email.value) && validity == true)
{
alert("Invalid E-mail Address! Please re-enter.")
frmComments.email.focus();
validity = false;
return false;
}
if(frmComments.zip.value == "" )
return true;
else
{
var pattern2 = /\d{5}/;
if(pattern2.test(frmComments.zip.value))
return true;
else
{
if(!pattern2.test(frmComments.zip.value) && validity == true)
{
alert("Invalid Zip Code! Must be in form 12345. Please re-enter.");
frmComments.zip.focus();
validity = false;
return false;
}
}
}
if(frmComments.phone.value == "")
return true;
else
{
var pattern3 = /\d{3}\-\d{3}\-\d{4}/;
if(pattern3.test(frmComments.phone.value))
return true;
else
{
if(!pattern3.test(frmComments.phone.value)&& validity == true)
{
alert("Invalid Phone Number! Must be in form 555-555-5555. Please
re-enter.");
frmComments.phone.focus();
validity = false;
return false;
}
}
}
}

function formSubmit()
{
window.event.returnValue = false;
if ( confirm ( "Are you sure you want to submit?" ) )
window.event.returnValue = true;
}
function formReset()
{
window.event.returnValue = false;
if ( confirm( "Are you sure you want to reset?" ) )
{
frmComments.name.focus();
window.event.returnValue = true;
}
}
// -->
</script>

<form id="frmComments"
action="http://matrix.csis.pace.edu/~f03-it604-s03/cgi-bin/comments.pl"
method="post" onSubmit="return validate(this);" onReset="return
formReset(this)">

<input type="submit" align="right" value="Submit" name="submit"
onclick="formSubmit()">

-----------------------------------------------------------
This is the link to the html page:

http://matrix.csis.pace.edu/~f03-it6.../comments.html

I tried to make the code easier to read by manually formatting it by
removeing the indents and line breaks. I don't know the technique you
suggested of formatting it with a certain number of columns. Please
let me know how to do that.

I am new to this group and may do things incorrectly until learn.

I don't know if you remember my problem of:

My phone validation doesn't work within my validate function. It works
alone, but not within this function like the other validations do.

Phone is not required, but if the user enters a phone number it must
be in the form of 555-555-5555.

Also, my submit confirmation dialog box comes up first and
continuously. I want it to appear last and once before final valid
submission.

Please let me know of a correct and better way of validating these
required fields: name, company, email, and validating phone for
correct format if user fills in phone number.

Thanks for your help.
Jul 20 '05 #1
21 6187
In article <c6*************************@posting.google.com> ,
ca*****@optonline.net enlightened us with...
<script language="JavaScript" type="text/javascript">
<!--
function validate(theForm)
{
var validity = true; // assume valid
if(frmComments.name.value=='' && validity == true)
{
alert('Your full name is required. Please enter your full name!');
validity = false;
frmComments.name.focus();
event.returnValue=false;
}
A simple return false would suffice.

frmComments.name.focus();
return false;
}
if(frmComments.zip.value == "" ) If the user didn't enter anything at all, value is undefined in some
browsers. Thus, you can't compare it to the null string. I had this type
of comparison fail miserably in a version of IE. So now, I do

if (!frmComments.zip || frmComments.zip.value == "")
return true;
else
{
var pattern2 = /\d{5}/;
if(pattern2.test(frmComments.zip.value))
return true;
else
{
if(!pattern2.test(frmComments.zip.value) && validity == true)
{
alert("Invalid Zip Code! Must be in form 12345. Please re-enter.");
frmComments.zip.focus();
validity = false;
No point in setting this if you return right after.
Actually, no point in it at all, since returning false after failure
prevents any more code from running.
return false;
}
}
}
if(frmComments.phone.value == "")
Again, test for the object, then the value.
You say it doesn't work, but you don't explain WHAT doesn't work. Does
it throw an error? Does it say it isn't valid when it is? Does it say it
is valid when it isn't?

function formSubmit()
{
window.event.returnValue = false; if ( confirm ( "Are you sure you want to submit?" ) )
window.event.returnValue = true;
return true would be fine.

if (confirm...) return true
else return false


<form id="frmComments"
action="http://matrix.csis.pace.edu/~f03-it604-s03/cgi-bin/comments.pl"
method="post" onSubmit="return validate(this);" onReset="return
formReset(this)">

<input type="submit" align="right" value="Submit" name="submit"
onclick="formSubmit()">


onClick fires BEFORE the onSubmit, so the confirm would fire first.
That's why that is happening. Remove it from the onClick of the submit
button and change onSubmit to...

onSubmit="if (validate(this)) formSubmit();"

Tell more about what's wrong with the phone validation after you change
this stuff and see if it still doesn't work.

--
~kaeli~
Why do people who know the least know it the loudest?
http://www.ipwebdesign.net/wildAtHeart
http://www.ipwebdesign.net/kaelisSpace

Jul 20 '05 #2
Thanks for your help.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #3
kaeli <ti******@NOSPAM.comcast.net> writes:
In article <c6*************************@posting.google.com> ,
ca*****@optonline.net enlightened us with...

event.returnValue=false;
}


A simple return false would suffice.


It also has the advantage of working in non-IE browsers. This code
uses "event" as a global variable, which only works in IE.
if(frmComments.zip.value == "" )

If the user didn't enter anything at all, value is undefined in some
browsers. Thus, you can't compare it to the null string. I had this type
of comparison fail miserably in a version of IE. So now, I do

if (!frmComments.zip || frmComments.zip.value == "")


You say that "value" is undefined, but check whether "zip" is defined.
Is this deliberate.

I ususally use
if (! elemRef.value) {...}
That works both if the value is undefined and if it is the empty string.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #4
In article <y8**********@hotpop.com>, lr*@hotpop.com enlightened us
with...

A simple return false would suffice.


It also has the advantage of working in non-IE browsers. This code
uses "event" as a global variable, which only works in IE.


I thought as much, but didn't want to say because I wasn't sure.

if (!frmComments.zip || frmComments.zip.value == "")


You say that "value" is undefined, but check whether "zip" is defined.
Is this deliberate.


Yes. In one of the browsers (I think it was IE5-something, but may have
been a netscape issue) if the user hadn't filled anything in, the test
for (element.value=="") threw an error unless I checked like the above.
I can't really explain why - could be a browser bug. I've just been
doing that for a while now and have had no more problems. *G*

Actually, I've these days I use my functions for validating. This is my
isBlank. Call like
if (isBlank(document.form1.elementname))

function isBlank(strObject)
{
/* Returns true if the field is blank, false if not.
You must pass in an input (text) object (not the value) */
var re = /\S+/;

if (!strObject) return true;
if (re.test(strObject.value)) return false;
else return true;
}
--
~kaeli~
Not one shred of evidence supports the notion that life is
serious.
http://www.ipwebdesign.net/wildAtHeart
http://www.ipwebdesign.net/kaelisSpace

Jul 20 '05 #5
kaeli <ti******@NOSPAM.comcast.net> writes:
Yes. In one of the browsers (I think it was IE5-something, but may have
been a netscape issue) if the user hadn't filled anything in, the test
for (element.value=="") threw an error unless I checked like the above.
Curious. That would definitly be a bug. If you find the browser, please
say so.
I can't really explain why - could be a browser bug. I've just been
doing that for a while now and have had no more problems. *G*
It's voodoo :)
Actually, I've these days I use my functions for validating. This is my
isBlank. Call like
if (isBlank(document.form1.elementname))
document.forms.form1.elementname
would be correct according to W3C DOM specification. I prefer
document.forms['form1'].elements['elementname']
but that's only a matter of style.
function isBlank(strObject)
{
/* Returns true if the field is blank, false if not.
You must pass in an input (text) object (not the value) */
var re = /\S+/;

if (!strObject) return true;
if (re.test(strObject.value)) return false;
else return true;


Just because I like to abbreviate logical tests:

return (!strObject || !/\S/.test(strObject.value));

(It always comes over me when I see something like
if (...) {return true;} else {return false;}
or
(...)?true:false
or the negation).

/L 'and don't get me started on (...)?1:0 ...'
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #6
In article <ll**********@hotpop.com>, lr*@hotpop.com enlightened us
with...

document.forms.form1.elementname
would be correct according to W3C DOM specification.
Really?
I've always seen the above.
I prefer
document.forms['form1'].elements['elementname']
but that's only a matter of style.
I prefer that when I'm coding for more than IE5/NN6 (intranet apps are
my main JS usage, so I get to not care so much about browsers).

Just because I like to abbreviate logical tests:

return (!strObject || !/\S/.test(strObject.value));

(It always comes over me when I see something like
if (...) {return true;} else {return false;}
or
(...)?true:false
or the negation).

/L 'and don't get me started on (...)?1:0 ...'


The way I code is completely dependent on who might modify it later and
what modifications might be done. It has to be easily understandable and
modifiable if it's shared code.
It's easier to add stuff to if/else blocks if they're already blocked
out. Like alerts when you're tracing problems. ;)

I happen to LOVE
x = y==3?0:1

But it's a bitch for people to understand later if they try to modify
it.
*LOL*

--
~kaeli~
The secret of the universe is @*&^^^ NO CARRIER
http://www.ipwebdesign.net/wildAtHeart
http://www.ipwebdesign.net/kaelisSpace

Jul 20 '05 #7
kaeli <ti******@NOSPAM.comcast.net> writes:
Really?
I've always seen the above.
Yep. There is nothing in the W3C DOM that requires the document object
to have properties corresponding to form names. Ofcourse, all browsers
have it, since people have been writing document.formName since
Netscape 2 (the first browser with Javascript support).

The document.forms collection is part of the W3C DOM, both v1 and v2.
It has also existed since Netscape 2.
The way I code is completely dependent on who might modify it later and
what modifications might be done. It has to be easily understandable and
modifiable if it's shared code.
Ah, readability and maintainability. That are acceptable reasons for
writing extra code.
It's easier to add stuff to if/else blocks if they're already blocked
out. Like alerts when you're tracing problems. ;)
Absolutely. I always add { } around by if-branches, because it prevents
stupid errors like
if (...) return false;
else
alert(foo);return true;
I happen to LOVE
x = y==3?0:1
For what?

At least make it
x= y==3?false:true;
Then it is obvious that the values represent a boolean result, not
numbers. I have yet to see a case where the value of (...)?0:1 was
used as a number. :)

Ofcourse, I prefer
x = y!=3;
and for extra readability I would name x something that sounded "boolean"
notEqual = y != 3;

It looks so much better to write
if(notEqual){ ... }
than
if(x){ ... }
The latter is probably what makes people write
if(x==true){ ... }
But it's a bitch for people to understand later if they try to modify
it.


Using boolean values for boolean results will definitly make it easier
to read. Not shorter, ofcourse.

/L :)
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #8
JRS: In article <c6*************************@posting.google.com> , seen
in news:comp.lang.javascript, AnnMarie <ca*****@optonline.net> posted at
Thu, 20 Nov 2003 20:45:50 :-
<script language="JavaScript" type="text/javascript">
<!--
function validate(theForm)
{
var validity = true; // assume valid
if(frmComments.name.value=='' && validity == true)
{
...


Code should be indented, by about two spaces per logical level, to show
its intended structure.

When a variable has a boolean value, there is no need to compare it with
true or false. "== true" above serves no purpose.

Code lines should not be machine-wrapped : your

alert('Your company name is required. Please enter the name of your
company!');

should be presented as

alert('Your company name is required.' +
' Please enter the name of your company!');

Cone that might be presented in News should be written in that manner;
otherwise, the author needs to format it before posting, in order that
it shall be conveniently readable.
Your RegExps presumably need to start with ^ and finish with $, as in
/^\d{5}$/ since otherwise they are only testing for the presence of, in
that case, five consecutive digits somewhere within the string.

The single RegExp /^$|^\d{5}$/ tests for (empty or 5 digits), in my
system. Similarly for phone numbers.

Writing

if (X) { return }
else ...

is pointless; return returns, and no else is required.

One should endeavour not to repeat very similar pieces of code that can
be parameterised and put into a function; this was discussed recently,
IIRC, and needs to be revived. The general case is that the function
needs to be supplied with the name of a field, a validating RegExp
(literal), and an error message or part thereof.

The entire testing then becomes a matter of ANDing function calls;
Message-ID <X2**************@merlyn.demon.co.uk> of 8 Nov 2003 refers,
"Validating Text box with multiple variables". That needs to be thought
about.
Read the FAQ; see below.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.
Jul 20 '05 #9
Thanks for your help. When I copy my indented code from an editor like
homesite to this newsgroup it doesn't copy the same way as it is
formatted. What is the best way to copy code to this newsgroup with the
indentation intact? Thanks.

AnnMarie

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #10
Lee
AnnMarie Caruso said:

Thanks for your help. When I copy my indented code from an editor like
homesite to this newsgroup it doesn't copy the same way as it is
formatted. What is the best way to copy code to this newsgroup with the
indentation intact? Thanks.


Configure your editor to use spaces instead of tabs for indentation.

Jul 20 '05 #11
In article <8y**********@hotpop.com>, lr*@hotpop.com enlightened us
with...
I happen to LOVE
x = y==3?0:1


For what?

At least make it
x= y==3?false:true;
Then it is obvious that the values represent a boolean result, not
numbers. I have yet to see a case where the value of (...)?0:1 was
used as a number. :)


I was giving that as an example. I meant the shortcut syntax.
I use it in java tons, like
String tmpString = request.getParameter("page");
int pg = tmpString==null?0:Integer.parseInt(tmpString);

If a value is boolean, I use true/false.

--
~kaeli~
User: The word computer professionals use when they mean
'idiot'.
http://www.ipwebdesign.net/wildAtHeart
http://www.ipwebdesign.net/kaelisSpace

Jul 20 '05 #12
JRS: In article <HM**************@merlyn.demon.co.uk>, seen in
news:comp.lang.javascript, Dr John Stockton <sp**@merlyn.demon.co.uk>
posted at Fri, 21 Nov 2003 16:49:17 :-

One should endeavour not to repeat very similar pieces of code that can
be parameterised and put into a function; this was discussed recently,
IIRC, and needs to be revived. The general case is that the function
needs to be supplied with the name of a field, a validating RegExp
(literal), and an error message or part thereof.

The entire testing then becomes a matter of ANDing function calls;
Message-ID <X2**************@merlyn.demon.co.uk> of 8 Nov 2003 refers,
"Validating Text box with multiple variables". That needs to be thought
about.

I have done so. The following is not quite ready to be put into,
perhaps, my js-tests.htm or elsewhere; I want to know whether the
comment marked *** being needed to balance the quotes to please W3's
TIDY is important (I expect the traditional <!-- ... --> would fix it).
Also, I want to set Chex within a function, in order to be able to
display it conveniently. It is a possible Web page, passing TIDY, which
illustrates how the checking of a simple Form can be fully
parameterised. Comment?

8<---

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML lang="en">

<HEAD><TITLE>Form Validator</TITLE></HEAD><BODY>

<H3>The Validation of Straightforward Forms</H3>

The validation of simple forms can be much compacted in comparison with
the usual lengthy approach, since the validation of each field is much
the same. Where fields need further checking, for example that dates are
valid or numbers within a numeric range, specific tests can be added
after the "pattern" tests.

<p>Most fields can be usefully validated, at least initially, with a
RegExp; for example<tt> /^$|^\d{3}$/ </tt>for being either empty or
three digits.

<p>For<tt> /./ </tt>one may prefer<tt> /^\S+$/ </tt>- no blanks and at
least one character.

<p>The form below is by default correctly filled in; try the test
button, then try the effect of errors in its fields.

<form name=Frm1 action=.>
GN <input type=text name=gn value="Jim" size=13><br>
FN <input type=text name=fn value="O'Reilly Hawkins" size=23><br>
CN <input type=text name=cn value="AA12345" size=13><br>
EM <input type=text name=em value="Ji*@Treasure.Is" size=33><br>
<input type=button name=Push value=" Test "
onClick="Ans.value=TryFrm(Chex)">
<input type=text name=Ans value="" size=13 readonly>
</form>

<script type="text/javascript">

with (Frm1) var Chex = [
[gn, "Given Name", "non-blank", /./],
[fn, "Family Name", "plausible", /^[A-Z' -]{2,}$/i], // ' ???
[cn, "Crew Number", "ZZ99999", /^[A-Z]{2}\d{5}$/],
[em, "E-address", "at least a@b.c", /^.+@.+\..+$/ ]
]

// Setup(Frm1, Chex)

function TryFrm(Chx) { var J, T // Pattern test any form
for (J=0 ; J < Chx.length ; J++) { T = Chx[J]
if (!T[3].test(T[0].value)) {
alert("Error in Field #" + (J+1) + " !\n" +
"Enter your " + T[1] + " please!\n" + "It should be " + T[2])
T[0].focus()
return false }
}
return true }

</script>

<p>The exact wording of the fixed and variable parts of the alert
message will need careful crafting, dependent on the circumstances, so
that the result always reads well.

<p>For a bit more elegance and typing, make the data an array of
objects.

<br><br><hr></BODY></HTML>

--->8

With more data in the array, the form generation could be automated; but
that looks rather like going too far.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.
Jul 20 '05 #13
Dr John Stockton <sp**@merlyn.demon.co.uk> writes:
I have done so. The following is not quite ready to be put into,
perhaps, my js-tests.htm or elsewhere; I want to know whether the
comment marked ***
I see no nothing marked "***" except right here.
.... Ah, you mean the comment marked "???" :)

being needed to balance the quotes to please W3's TIDY is important
What do you mean by "important". I would say that only Tidy (which is
no longer W3's) would care about that quote, so it's not important
unless you need to use Tidy.

If you don't want the comment, but want to retain Tidy-compatability,
you can escape the quote in the regexp, i.e., write \' instead of '.
The regexp is equivealent.
(I expect the traditional <!-- ... --> would fix it).
Also, I want to set Chex within a function, in order to be able to
display it conveniently. It is a possible Web page, passing TIDY, which
illustrates how the checking of a simple Form can be fully
parameterised. Comment?
It looks very much like some code I have recently made, currently only
described in Danish (but the code is in Javascript and the code
comments are English, so it might be understandable anyway)
<URL:http://www.infimum.dk/HTML/validering.html>

Instead of parameterizing with regular expressions, I use general
functions that return either true or false (or a string with an
extended error message). Ofcourse, I have a function to make test
functions from regular expressions. :)
<p>The form below is by default correctly filled in; try the test
button, then try the effect of errors in its fields.

<form name=Frm1 action=.>
I would recommend an action of
action=""
instead. The "." gives the current directory in some browsers,
and probably something else in other browsers. An empty URL
fragment will point to the current file.
(I know it's just an example, just another pet peeve :)
GN <input type=text name=gn value="Jim" size=13><br>
FN <input type=text name=fn value="O'Reilly Hawkins" size=23><br>
CN <input type=text name=cn value="AA12345" size=13><br>
EM <input type=text name=em value="Ji*@Treasure.Is" size=33><br>
<input type=button name=Push value=" Test "
onClick="Ans.value=TryFrm(Chex)">
<input type=text name=Ans value="" size=13 readonly>
</form>

<script type="text/javascript">

with (Frm1) var Chex = [
You assume Frm1 is a global variable pointing to the form of that name.
I would use
with (document.forms['Frm1'].elements)
although the "elements" part can probably be skipped.
[gn, "Given Name", "non-blank", /./],
[fn, "Family Name", "plausible", /^[A-Z' -]{2,}$/i], // ' ???
[cn, "Crew Number", "ZZ99999", /^[A-Z]{2}\d{5}$/],
[em, "E-address", "at least a@b.c", /^.+@.+\..+$/ ]
]
// Setup(Frm1, Chex)

function TryFrm(Chx) { var J, T // Pattern test any form
for (J=0 ; J < Chx.length ; J++) { T = Chx[J]
if (!T[3].test(T[0].value)) {
alert("Error in Field #" + (J+1) + " !\n" +
"Enter your " + T[1] + " please!\n" + "It should be " + T[2])
T[0].focus()
return false }
You stop after the first error. Since you have all the tests available,
I would test them all and report all the errors at once. Usability-wise
that is better than having to attempt to submit for every error.
}
return true }

</script>

<p>The exact wording of the fixed and variable parts of the alert
message will need careful crafting, dependent on the circumstances, so
that the result always reads well.
If space is not that important, you could store the entire error
message, and not have to always combine it using the same template.
With more data in the array, the form generation could be automated; but
that looks rather like going too far.


Agree.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #14
JRS: In article <Kz**************@merlyn.demon.co.uk>, seen in
news:comp.lang.javascript, Dr John Stockton <sp**@merlyn.demon.co.uk>
posted at Fri, 21 Nov 2003 22:11:14 :-

I have done so. The following is not quite ready to be put into,
perhaps, my js-tests.htm or elsewhere;


For the time being, the page should be at <URL:http://www.merlyn.demon.
co.uk/jt.htm>; do not link to it there. That in the previous post is
substantially unchanged, but supplemented by an objectified version
with an effective way of invoking more specific tests on specific
fields, and by better text.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.
Jul 20 '05 #15
JRS: In article <r8**********@hotpop.com>, seen in
news:comp.lang.javascript, Lasse Reichstein Nielsen <lr*@hotpop.com>
posted at Sat, 22 Nov 2003 02:46:01 :-
Dr John Stockton <sp**@merlyn.demon.co.uk> writes:
I have done so. The following is not quite ready to be put into,
perhaps, my js-tests.htm or elsewhere; I want to know whether the
comment marked ***
I see no nothing marked "***" except right here.
... Ah, you mean the comment marked "???" :)


Oops!
being needed to balance the quotes to please W3's TIDY is important


What do you mean by "important". I would say that only Tidy (which is
no longer W3's) would care about that quote, so it's not important
unless you need to use Tidy.


I do. It finds so much that needs attention, so readily. It takes me,
after editing the source of a page, 2 clicks, 3 keystrokes, and 4
seconds overall to get a TIDY report and to see whether it is clean.
If you don't want the comment, but want to retain Tidy-compatability,
you can escape the quote in the regexp, i.e., write \' instead of '.
The regexp is equivealent.
Done. Unfortunately, I don't see how to explain, in the 8 characters
allowable in that end-of-that-line comment, why \' is used, unless the
comment contains ', which ... . OK, done it.
I would recommend an action of
action=""
instead. The "." gives the current directory in some browsers,
and probably something else in other browsers. An empty URL
fragment will point to the current file.
(I know it's just an example, just another pet peeve :)
The action has to be there to get a clean TIDY result, and for that it
needs more parameter than just "". Test now points this out. I never
use Actions.

with (Frm1) var Chex = [


You assume Frm1 is a global variable pointing to the form of that name.
I would use
with (document.forms['Frm1'].elements)
although the "elements" part can probably be skipped.


Yes, that's how I generally do it. Except that VB-dates.htm has such as
document.forms.Frm1.Yr1.value = Yr ...

Done, for the "Object Data" version, but mutated for current
circumstances. "Array Data" is obsolescent.

You stop after the first error. Since you have all the tests available,
I would test them all and report all the errors at once. Usability-wise
that is better than having to attempt to submit for every error.


That follows common usage such as earlier in the thread. I have now
done it with a third test button and a third function. OTOH, those who
make too many errors should be more careful; or the fields could be
tested onBlur using a similar but loop-less function, which needs
another Form.

<p>The exact wording of the fixed and variable parts of the alert
message will need careful crafting, dependent on the circumstances, so
that the result always reads well.


If space is not that important, you could store the entire error
message, and not have to always combine it using the same template.


I think that is near enough equivalent to making the fixed part near-
empty and putting more in the variable parts.

See, if you wish, <URL:http://www.merlyn.demon.co.uk/jt.htm>, revised.

Thanks.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.
Jul 20 '05 #16
Dr John Stockton <sp**@merlyn.demon.co.uk> writes:
JRS: In article <r8**********@hotpop.com>, seen in
news:comp.lang.javascript, Lasse Reichstein Nielsen <lr*@hotpop.com>
posted at Sat, 22 Nov 2003 02:46:01 :-
This "JRS:" at the start always confuzes me. I start out thinking you
are replying to yourself :)
Done. Unfortunately, I don't see how to explain, in the 8 characters
allowable in that end-of-that-line comment, why \' is used, unless the
comment contains ', which ... . OK, done it.
You did it in 7: "// \ TIDY" :)
The action has to be there to get a clean TIDY result, and for that it
needs more parameter than just "". Test now points this out. I never
use Actions.
You should! From the form element specification in HTML 4.01:
---
action %URI; #REQUIRED -- server-side form handler --
---
^^^^^^^^^!
The minimal URI fragment is the empty string. If TIDY refuses that,
"#" is usually harmless. Better yet, add an URL to a page that
explains that the previous page requires Javascript :)
See, if you wish, <URL:http://www.merlyn.demon.co.uk/jt.htm>, revised.


Looks fine (and uncovered a bug in Opera's Function.prototype.toString
- it didn't unparse regexp literals, but just wrote "object" in their
place).

Wrt:
---
with (document.forms[Frm]) return [
// elements: [F:Field, W:"What", H:"How", R:RegExp, ?V:ValidFn]
{F:gn, W:"Given Name", H:"non-blank", V:GNbad},
---
I recommend not referring to the elements directly, but just their name:
---
return [
// elements: [F:"FieldName", W:"What", H:"How", R:RegExp, ?V:ValidFn]
{F:"gn", W:"Given Name", H:"non-blank", V:GNbad},
---
The advantage is that you can then create the object array before
the form has been loaded. It might not be needed, but I like to keep
the opportunity open.

Do you have any plans for handling radiobutton groups?

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #17
JRS: In article <4q**********@hotpop.com>, seen in
news:comp.lang.javascript, Lasse Reichstein Nielsen <lr*@hotpop.com>
posted at Sun, 23 Nov 2003 03:37:39 :-
Dr John Stockton <sp**@merlyn.demon.co.uk> writes:
JRS: In article <r8**********@hotpop.com>, seen in
news:comp.lang.javascript, Lasse Reichstein Nielsen <lr*@hotpop.com>
posted at Sat, 22 Nov 2003 02:46:01 :-
This "JRS:" at the start always confuzes me. I start out thinking you
are replying to yourself :)


I find it useful when someone quotes a response of mine without giving
any new attribution.

The action has to be there to get a clean TIDY result, and for that it
needs more parameter than just "". Test now points this out. I never
use Actions.


You should! From the form element specification in HTML 4.01:
---
action %URI; #REQUIRED -- server-side form handler --
---
^^^^^^^^^!
The minimal URI fragment is the empty string. If TIDY refuses that,
"#" is usually harmless. Better yet, add an URL to a page that
explains that the previous page requires Javascript :)


"#" is OK. But what I meant was that, though I set action= in forms to
please Tidy, I have no need of setting an action to be performed. My
forms do not submit, and are present for modularisation. It's something
I've never felt a need to use.

Could I use <div ID=FrmX> instead, without too many other changes?
OTOH, *this* case is an example of something that might need to be
Submitted ...
Wrt:
---
with (document.forms[Frm]) return [
// elements: [F:Field, W:"What", H:"How", R:RegExp, ?V:ValidFn]
{F:gn, W:"Given Name", H:"non-blank", V:GNbad},
---
I recommend not referring to the elements directly, but just their name:
---
return [
// elements: [F:"FieldName", W:"What", H:"How", R:RegExp, ?V:ValidFn]
{F:"gn", W:"Given Name", H:"non-blank", V:GNbad},
---
The advantage is that you can then create the object array before
the form has been loaded. It might not be needed, but I like to keep
the opportunity open.
A disadvantage is that, for me, it does not work. Probably it requires
another document.forms[] or suchlike where F is used. Not tonight.

Do you have any plans for handling radiobutton groups?


I only use one set, in js-anclk.htm, used in function Do() - I don't see
what you are implying could be done, as they should not need validation.

--
© John Stockton, Surrey, UK. ??*@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.

In MS OE, choose Tools, Options, Send; select Plain Text for News and E-mail.
Jul 20 '05 #18
Dr John Stockton <sp**@merlyn.demon.co.uk> writes:
"#" is OK. But what I meant was that, though I set action= in forms to
please Tidy, I have no need of setting an action to be performed. My
forms do not submit, and are present for modularisation. It's something
I've never felt a need to use.

Could I use <div ID=FrmX> instead, without too many other changes?
Probably not.
Using a form around the input controls means:
- you can access the form using document.forms, and the controls using
form.elements. Without a form, no elements collection.
- Each control has a form property that points to the form. That makes
it easy to go from one control to another (e.g.
onclick="this.form.elements['otherControl'].value = 'foo';"
)
- Submit buttons makes sense, and you have somewhere to add the onsubmit
handler.
All in all, without a form element, input controls are completely
unrelated.
A disadvantage is that, for me, it does not work. Probably it requires
another document.forms[] or suchlike where F is used.
Exactly.
Do you have any plans for handling radiobutton groups?

I only use one set, in js-anclk.htm, used in function Do() - I don't see
what you are implying could be done, as they should not need validation.


You could require that one of them was checked. However, just starting
one of them out as checked would ensure that.

I have never seen the need for checkbox groups, so I can't say what
you would want to validate them for. But they work line radiobutton
groups, i.e., formRef.elements.cbgroupName gives a collection.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #19
JRS: In article <65**********@hotpop.com>, seen in
news:comp.lang.javascript, Lasse Reichstein Nielsen <lr*@hotpop.com>
posted at Mon, 24 Nov 2003 01:59:37 :-
Dr John Stockton <sp**@merlyn.demon.co.uk> writes:
A disadvantage is that, for me, it does not work. Probably it requires
another document.forms[] or suchlike where F is used.


Exactly.


Done; and the form name string is now included in the parameter.

I see no benefit of continuing with FTry1 and PrepArr; unless someone
persuades me otherwise, I will remove them and continue only with FTry2,
FTry3 & PrepObj.

There is a new page, <URL:http://www.merlyn.demon.co.uk/js-valid.htm>;
it can be bookmarked and linked but is not yet worth visiting for those
who know of jt.htm.

Do you have any plans for handling radiobutton groups?

I only use one set, in js-anclk.htm, used in function Do() - I don't see
what you are implying could be done, as they should not need validation.


You could require that one of them was checked. However, just starting
one of them out as checked would ensure that.


In a radio group, ISTM that one should be normally able to return to the
starting point without restoring other settings. Therefore, if "none"
is to be basically allowed, there should be an associated checkbox which
disables the group (while retaining the setting). All accessible
combinations should be valid. This presumes that one is prepared to
supply a default -- but "How many legs does your pet have? "o 0 / o 2 /
o 4 / o more / o other" might be considered not to have a reasonable
default.

I have never seen the need for checkbox groups, so I can't say what
you would want to validate them for. But they work line radiobutton
groups, i.e., formRef.elements.cbgroupName gives a collection.


In a checkbox group, it could be that only certain patterns are
permissible; for example, if they were a Hamming? code. The group can
be validated, but an individual click cannot; it seems necessary to do
three clicks at once in order to only go through valid settings.
Therefore, post-validation might be essential; but good design will
avoid it if possible.

H'mmm ... I had, as I wrote that,

f = document.forms[Chx.FN].elements[F] // F a string
if ( R && !R.test(f.value) || ( V && V(f.value) ) )

Ah!

if ( R && !R.test(f.value) || ( V && V(f) ) )

and each existing function V now gains an internal .value .

Where FN => f refers to checkboxes, now the programmer just has to
provide a compatible V. This will also work for grummits and oozlums,
if and when browsers implement such controls.

A crude Radiobutton validation is demonstrated.
As a list of potentially validatable controls, I have :
Those with .value (string or otherwise)
Radiobuttons
Checkboxes
Is that all?

V is now inverted; one hopes for true, not false.

It might be possible to put, as a final element of the array, at least
for FTry2,
{F:"TheForm", W:"All", H:"Right", V:FormIsOK}
where FormIsOK checks the form overall knowing that the elements are
plausible.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.
Jul 20 '05 #20
Dr John Stockton <sp**@merlyn.demon.co.uk> writes:
In a radio group, ISTM that one should be normally able to return to the
starting point without restoring other settings. Therefore, if "none"
is to be basically allowed, there should be an associated checkbox which
disables the group (while retaining the setting).
That could be a radio button too ("none of the above"). It would
automatically reset the other radio buttons.
All accessible combinations should be valid. This presumes that one
is prepared to supply a default -- but "How many legs does your pet
have? "o 0 / o 2 / o 4 / o more / o other" might be considered not
to have a reasonable default.
I would say any of them would be a reasonable default (although 4 is
probably the most common). You will have to change it if the default
is incorrect, but that is no worse than having to click because there
is no default.
In a checkbox group, it could be that only certain patterns are
permissible; for example, if they were a Hamming? code. The group can
be validated, but an individual click cannot; it seems necessary to do
three clicks at once in order to only go through valid settings.
Therefore, post-validation might be essential; but good design will
avoid it if possible.
A Hamming code would be a weird thing to enter. It would also be a prime
candidate for automatically updating itself when you click on something.
if ( R && !R.test(f.value) || ( V && V(f) ) )

and each existing function V now gains an internal .value .
That should work.
Where FN => f refers to checkboxes, now the programmer just has to
provide a compatible V. This will also work for grummits and oozlums,
if and when browsers implement such controls.
I can hardly wait :)
As a list of potentially validatable controls, I have :
Those with .value (string or otherwise)
Radiobuttons
Checkboxes
Is that all?
Almost. :)

All currently possible controls are:

input type=text
input type=password
input type=file
input type=button
input type=submit
input type=image
input type=reset
input type=radiobutton
input type=checkbox
textarea
select
button type=button
button type=submit
button type=reset
object

Objects are special (I have never seen them used, and it's pretty
much up to the included object what it means).

All the rest have values.
All of them can share names so elements['name'] becomes a collection,
not only radiobuttons and checkboxes.

The only problem is that in earlier browsers (e.g., Netscape 4), select
elements didn't have values. Instead of
selectRef.value
you had to get the value from the selected option
selectRef.options[selectRef.selectedIndex].value

You can't trust the value of a select element with the multiple
attribute, since it only refers to the first selected option.

It shouldn't be a problem, since a select element is restricted to the
options provided by the page author, so there should be no need to
validate.

V is now inverted; one hopes for true, not false.
More intuitive. In my version, I allowed the function to also return a
string to represent false. That string was then used as the error message.
It might be possible to put, as a final element of the array, at least
for FTry2,
{F:"TheForm", W:"All", H:"Right", V:FormIsOK}
where FormIsOK checks the form overall knowing that the elements are
plausible.


That can catch the one thing the simple testing doesn't: inter-control
dependencies.

Another alternative is to allow the field part {F:"fn"} to be an array,
and in that case call the validation function with all the elements
as arguments (probably using the apply method).

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #21
JRS: In article <sm**********@hotpop.com>, seen in
news:comp.lang.javascript, Lasse Reichstein Nielsen <lr*@hotpop.com>
posted at Mon, 24 Nov 2003 22:31:55 :-
Dr John Stockton <sp**@merlyn.demon.co.uk> writes:
In a radio group, ISTM that one should be normally able to return to the
starting point without restoring other settings. Therefore, if "none"
is to be basically allowed, there should be an associated checkbox which
disables the group (while retaining the setting).
That could be a radio button too ("none of the above"). It would
automatically reset the other radio buttons.


The ideal solution, but in conflict with the actual case stipulated!

In a checkbox group, it could be that only certain patterns are
permissible; for example, if they were a Hamming? code. The group can
be validated, but an individual click cannot; it seems necessary to do
three clicks at once in order to only go through valid settings.
Therefore, post-validation might be essential; but good design will
avoid it if possible.


A Hamming code would be a weird thing to enter. It would also be a prime
candidate for automatically updating itself when you click on something.


But, since a single change gives a wrong code which is nearer to the old
code than it is to any other correct code, the only logical change would
be to unclick. However, there must be a more normal example of a set of
checkboxes where the number of entries is limited : A child has three
aunts, each of whom is willing to give any one out of a list of six
presents; the child must therefore select up to three checkboxes.

if ( R && !R.test(f.value) || ( V && V(f) ) )

and each existing function V now gains an internal .value .


That should work.


It does. It is now !V(f, P) where P is an optional parameter, whose
default value is undefined (as opposed to not defined). Tested in
function AgeOK, with P:{L:9,H:13}}.

In my version, I allowed the function to also return a
string to represent false. That string was then used as the error message.
It does mean that, unless the string can be supplied as a parameter to
the function, or chosen by a parameter, that the same function may be
less readily re-usable for other fields; an embedded string needs to
match all possible uses of the function, and might not be so well
understood.

Before I read your page, I thought I couldn't read Danish. I now know
that I cannot. But I suggest a link from that page to its hierarchical
parent.
Another alternative is to allow the field part {F:"fn"} to be an array,
and in that case call the validation function with all the elements
as arguments (probably using the apply method).


In most cases, another array would be needed to accommodate the
different messages needed; but one could have
F:[{"fn1","msg1"},{"fn2","msg2"}, ...]
and it amounts to having the same leaves on the tree of data whilst
rearranging the branches. However, in this case one leaf can be on many
branches.

I assume that, in

Q = new Object of some large and expensive sort
A = {j:{x:1,y:2,z:Q}, k{a:4,b:5}}
A.k.c = Q

the third statement is cheap in time and memory usage. And in fact
<anything> = Q is cheap.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/&c., FAQqy topics & links;
<URL:http://www.merlyn.demon.co.uk/clpb-faq.txt> RAH Prins : c.l.p.b mFAQ;
<URL:ftp://garbo.uwasa.fi/pc/link/tsfaqp.zip> Timo Salmi's Turbo Pascal FAQ.
Jul 20 '05 #22

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

Similar topics

1
by: Efrat Regev | last post by:
Hello, I would like to recurse through a directory and make files (which match a specific criteria) read only. From searching the Internet, I found...
1
by: Mike | last post by:
Hello, I can't find any javascript that reads and writes cookies with keys, so that it is compatible with ASP (I want to read and write cookies from both javascript and ASP) for example in...
1
by: samuelgreene | last post by:
Hello, I have a front-end access db on a server share - the users should COPY the db to their desktop - but we know how that goes. I've tried to make it read only and have denied execute...
4
by: Srinivas Kollipara | last post by:
Hey guys, i have a small question in C#. I have a windows form which has Address fields, zip code and phone number fields. it is working fine with U.S. but i need to modify that for all the other...
8
by: goldtech | last post by:
Newbie esp about html validation - seems like something to strive for. Yet many pages even "enterprise" corporate type pages do not validate, yet seem to display well on most browsers. Two...
1
by: Sankalp | last post by:
Hi I am writing a large program where I am using three text boxes. I am performing validation controls on these text boxes however there are some conditions Names of textboxes 1. x 2. y 3. z...
12
by: tadisaus2 | last post by:
Hello, Checkbox form validation - how to make a user select 4 check boxes? I have a question of a few checkboxes and how do I require a user to check 2 checkboxes (no more, no less)? Here is my...
1
by: jhansi | last post by:
hi... I have created a form it's working properly.... but i want to consider phone number and STD code in two different text field for a single lable phone number..... and I have considered...
1
by: awigren | last post by:
I have already created a way to add new data in my database through a 3-step process. Now that I have all my methods of entering data set, I am now wondering if there is any way to make a...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
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,...
0
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...

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.