473,732 Members | 2,210 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

<script language="JavaS cript" type="text/javascript">
<!--
function validate(theFor m)
{
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.nam e.focus();
event.returnVal ue=false;
}
if(frmComments. company.value== '' && validity == true)
{
alert('Your company name is required. Please enter the name of your
company!');
validity = false;
frmComments.com pany.focus();
event.returnVal ue=false;
}
var pattern1 = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4 })+$/;
if (!pattern1.test (frmComments.em ail.value) && validity == true)
{
alert("Invalid E-mail Address! Please re-enter.")
frmComments.ema il.focus();
validity = false;
return false;
}
if(frmComments. zip.value == "" )
return true;
else
{
var pattern2 = /\d{5}/;
if(pattern2.tes t(frmComments.z ip.value))
return true;
else
{
if(!pattern2.te st(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.tes t(frmComments.p hone.value))
return true;
else
{
if(!pattern3.te st(frmComments. phone.value)&& validity == true)
{
alert("Invalid Phone Number! Must be in form 555-555-5555. Please
re-enter.");
frmComments.pho ne.focus();
validity = false;
return false;
}
}
}
}

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

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

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

-----------------------------------------------------------
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 6246
In article <c6************ *************@p osting.google.c om>,
ca*****@optonli ne.net enlightened us with...
<script language="JavaS cript" type="text/javascript">
<!--
function validate(theFor m)
{
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.nam e.focus();
event.returnVal ue=false;
}
A simple return false would suffice.

frmComments.nam e.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.z ip || frmComments.zip .value == "")
return true;
else
{
var pattern2 = /\d{5}/;
if(pattern2.tes t(frmComments.z ip.value))
return true;
else
{
if(!pattern2.te st(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.re turnValue = false; if ( confirm ( "Are you sure you want to submit?" ) )
window.event.re turnValue = true;
return true would be fine.

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


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

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


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******@NOSPA M.comcast.net> writes:
In article <c6************ *************@p osting.google.c om>,
ca*****@optonli ne.net enlightened us with...

event.returnVal ue=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.z ip || 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/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #4
In article <y8**********@h otpop.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.z ip || 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(docume nt.form1.elemen tname))

function isBlank(strObje ct)
{
/* 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(strObj ect.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******@NOSPA M.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(docume nt.form1.elemen tname))
document.forms. form1.elementna me
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(strObje ct)
{
/* 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(strObj ect.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:fals e
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/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #6
In article <ll**********@h otpop.com>, lr*@hotpop.com enlightened us
with...

document.forms. form1.elementna me
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:fals e
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******@NOSPA M.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.formNa me 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);retu rn 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/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #8
JRS: In article <c6************ *************@p osting.google.c om>, seen
in news:comp.lang. javascript, AnnMarie <ca*****@optonl ine.net> posted at
Thu, 20 Nov 2003 20:45:50 :-
<script language="JavaS cript" type="text/javascript">
<!--
function validate(theFor m)
{
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.demo n.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demo n.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

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

Similar topics

1
5208
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 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303343 which shows how to change file attributes to read only using the win32api module. That's great, but I was hoping there's a more portable way to do so. Is there a more portable API call to make files read only? Many Thanks,
1
2224
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 ASP: <% Response.Cookies("user")("firstname")="John" Response.Cookies("user")("lastname")="Smith"
1
2042
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 permissions on the directory but it's still runs off the server - i just get the read only message in access. Does anyone have a solution? Why am I able to execute the db? Is a temporary copy being created on the desktop computer? I've noticed
4
11732
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 countries. is there any way i can validate zipcode and phone numbers.... Thanks in advance. bye Srinivas
8
1785
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 questions: 1. What is the reward, the reason to strive for a validating page? 2. Given the code snippet below which does not validate - how can accomplish the same "look" with code that does validate? Please without CSS, just html. Thanks ....
1
1136
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 The conditions are
12
2887
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 form: <input type="checkbox" name="color" id="q" value="a" />A<BR /> <input type="checkbox" name="color" id="q2" value="b" />b<BR /> <input type="checkbox" name="color" id="q3" value="c" />c<BR /> <input type="checkbox" name="color" id="q4"...
1
5904
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 the fields like first name,last name,Date of birth, Phone Number ,mobile number and address... 1)If i enter all the fields then only the values should enter into the database... 2) if i dint enter the mobile field then also it should save into...
1
1354
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 "Read-Only" form or table to view the data, so that when others are using the database to look up information, nothing can be accidently changed. Thanks.
0
8946
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8774
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9307
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9235
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9181
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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

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