473,756 Members | 1,881 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

IF Statement Problems (or possibly not!)

I'm writing an if statement for a UK credit card form validation
script. Users who specify that their card is Switch need to enter
either the issue number or the 'valid from' date.

I'm trying to write an if statement so that if:

1. The word "Month" is in the validFromMonth field (where they haven't
selected a month a the drop-down menu) or the word "Year" is in the
validFromYear field (where they haven't selected a year another the
drop-down menu)
OR
2. Nothing has been entered in the text box for the Issue_Number

then the alert box appears

<SCRIPT language="text/javascript">
function checkform()
{
if (document.Final .Cardtype.value == "")
{
alert("Please specify the type of debit or credit card.");
return false;
}
if (document.Final .Cardholder.val ue == "")
{
alert("Please enter the Cardholder's Name.");
return false;
}
if (document.Final .Cardnumber.val ue == "")
{
alert("Please enter the card number.");
return false;
}
//check whether they need to supply an issue number/start date
var cc_type = document.Final. Cardtype.option s[document.Final. Cardtype.select edIndex].value;
if (cc_type == "Switch")
{
// if card is Switch then we need an issue number or start date

var IssNum = document.Final. Issue_Number.va lue
var fromM = document.Final. validFromMonth. value
var fromY = document.Final. validFromYear.v alue

if ((IssNum == "") || ((fromM == "Month") || (fromY == "Year")))
{
alert("You must supply an issue number or a 'Valid From' date for
Switch");
return false;
}
}
// if we reach this point then we submit the form.
return true;
}
//-->
</script>

By enclosing (fromM == "Month") || (fromY == "Year") in their own
brackets, I was hoping it would evaluate that first but it doesn't
seem to be working. The form wants a correct entry in all three before
allowing progress.

[I know I haven't written the checking bit for the expiry date yet,
I'm doing it in order!]

Any ideas?
Jul 23 '05 #1
3 1738
> if ((IssNum == "") || ((fromM == "Month") || (fromY == "Year")))
{
alert("You must supply an issue number or a 'Valid From' date for
Switch");
return false;


The problem is that is IssNum != "" it still goes and validates the
other. This will never pass because unless you fill in ALL the blanks
it would never pass. the complecated thing is that you have to check
for all invalid combinations.

// issue number not filled in, and no month or year.
if ((IssNum == "") && ((fromM=="Month ") || (fromY=="Year") ))
{
alert("You must supply an issue number or....");
}

Though this will pass is someone enters an issue number and a valid
date. If you don't want that you should add that exception with an
or.

Good luck,
Vincent

Jul 23 '05 #2
What's your point? I mean, what the problem is?

ccton
--
www.vicdir.com
"Mark Morton" <ma**@bustingmy chops.com> ????
news:e4******** *************** ***@posting.goo gle.com...
I'm writing an if statement for a UK credit card form validation
script. Users who specify that their card is Switch need to enter
either the issue number or the 'valid from' date.

I'm trying to write an if statement so that if:

1. The word "Month" is in the validFromMonth field (where they haven't
selected a month a the drop-down menu) or the word "Year" is in the
validFromYear field (where they haven't selected a year another the
drop-down menu)
OR
2. Nothing has been entered in the text box for the Issue_Number

then the alert box appears

<SCRIPT language="text/javascript">
function checkform()
{
if (document.Final .Cardtype.value == "")
{
alert("Please specify the type of debit or credit card.");
return false;
}
if (document.Final .Cardholder.val ue == "")
{
alert("Please enter the Cardholder's Name.");
return false;
}
if (document.Final .Cardnumber.val ue == "")
{
alert("Please enter the card number.");
return false;
}
//check whether they need to supply an issue number/start date
var cc_type = document.Final. Cardtype.option s[document.Final. Cardtype.select edIndex].value
; if (cc_type == "Switch")
{
// if card is Switch then we need an issue number or start date

var IssNum = document.Final. Issue_Number.va lue
var fromM = document.Final. validFromMonth. value
var fromY = document.Final. validFromYear.v alue

if ((IssNum == "") || ((fromM == "Month") || (fromY == "Year")))
{
alert("You must supply an issue number or a 'Valid From' date for
Switch");
return false;
}
}
// if we reach this point then we submit the form.
return true;
}
//-->
</script>

By enclosing (fromM == "Month") || (fromY == "Year") in their own
brackets, I was hoping it would evaluate that first but it doesn't
seem to be working. The form wants a correct entry in all three before
allowing progress.

[I know I haven't written the checking bit for the expiry date yet,
I'm doing it in order!]

Any ideas?

Jul 23 '05 #3
Mark Morton wrote:
I'm writing an if statement for a UK credit card form validation
script. Users who specify that their card is Switch need to enter
either the issue number or the 'valid from' date.
Whatever validation you do on the client _must_ be duplicated on the server. The client-side
validation is for the user's benefit only, there are any number of ways of submitting the form
without completing the form as specified in your client-side validation.
I'm trying to write an if statement so that if:

1. The word "Month" is in the validFromMonth field (where they haven't
selected a month a the drop-down menu) or the word "Year" is in the
validFromYear field (where they haven't selected a year another the
drop-down menu)
OR
2. Nothing has been entered in the text box for the Issue_Number

then the alert box appears

<SCRIPT language="text/javascript">
<script type="text/javascript">

The LANGUAGE attribute is deprecated, and used incorrectly above.
function checkform()
Presumably you're using <form ... onsubmit="retur n checkform();">? Change it to <form ...
onsubmit="retur n checkform(this) ;"> and the function definition above to be:

function checkform(myFor m)
{
if (document.Final .Cardtype.value == "")
I'm assuming Cardtype is a <select>? If so, use

if (myForm.element s['Cardtype'].options[myForm.elements['Cardtype'].selectedIndex].value == "")

Or if the first <option> is the empty one, simply:

if (myForm.element s['Cardtype'].selectedIndex == 0)

if (document.Final .Cardholder.val ue == "")
if (myForm.element s['Cardholder'].value == "")

Note that if the user enters one or more spaces, this test will think the input has data in it. To
fix this, use the string manipulation at:

<url: http://jibbering.com/faq/#FAQ4_16 />

Then you can use:

if (myForm.element s['Cardholder'].value.trim() == "")
if (document.Final .Cardnumber.val ue == "")
Same as above.
//check whether they need to supply an issue number/start date
var cc_type = document.Final. Cardtype.option s[document.Final. Cardtype.select edIndex].value;
You're retrieving the value of a <select> correctly here, yet above and below this you seem to be
doing it by simply retrieving the .value attribute of the <select>. Also, you should do this
earlier, then you can use cc_type to test whether they've selected a CC type at all.
if (cc_type == "Switch")
{
// if card is Switch then we need an issue number or start date

var IssNum = document.Final. Issue_Number.va lue
var fromM = document.Final. validFromMonth. value
var fromY = document.Final. validFromYear.v alue
Retrieve these <select> values using the syntax shown earlier.
if ((IssNum == "") || ((fromM == "Month") || (fromY == "Year")))
From your surrounding text and output of the alert(), I'm assuming you need either an issue number
or valid "From" date. So your logic is (in english): show an error when IssNum is empty, or fromM
is "Month" and fromY is "Year" (because that means a complete date hasn't been chosen). Converting
this to Javascript gets you:

if (IssNum == "" || (fromM == "Month" && fromY == "Year"))

The brackets are not actually required since && has higher precedence then ||, but I like to make
the intent clear.
//-->
Not needed. Omit.
</script>

By enclosing (fromM == "Month") || (fromY == "Year") in their own
brackets, I was hoping it would evaluate that first but it doesn't
seem to be working. The form wants a correct entry in all three before
allowing progress.
Javascript evaluates conditions from left to right (observing precedence rules and brackets on the
way). Once it's determined conclusively the truth or falseness of the entire condition, it stops
evaluating. This means if you do something like:

if (false && whateverElseYou WantToTest())

the function "whateverElseYo uWantToTest()" will _never_ be executed. Javascript sees the result of
the part before the && is false. It's an &&, both expressions _must_ be true for the entire
condition to be true, but the first expression is false. It does not matter what the second
expression returns, the entire condition will always be false, so Javascript stops after seeing
"false".

This is what allows you to do:

if (someObject != null && someObject.some Method())

normally, trying to call someMethod() on a null someObject would cause an error, but when
someObject == null, the first expression of the && is false, therefore the entire condition is
false and Javascript never even executes the 2nd expression. This lets you do things like:

With a set of || conditions, Javascript must always evaluate all 3 expressions to determine if any
of them are true.

But in your case the logic was simply wrong.
Any ideas?


Doing it the way you are doing it is annoying, because you tell the person one thing they did
wrong, then they correct that and try to submit again only to be told the next thing they did
wrong, so they correct that, then they're told the 3rd thing they did wrong, and so on.

Better to build a string containing all the mistakes they made and alert everything at once.

Something like:

var errorMsg = [];
var firstFieldToFoc us;
if (formField1 != 'whatever') {
errorMsg.push(' Test1 failed');
if (!firstFieldToF ocus) {
firstFieldToFoc us = formField1;
}
}
if (formField2 != 'whatever') {
errorMsg.push(' Test2 failed');
if (!firstFieldToF ocus) {
firstFieldToFoc us = formField2;
}
}
// etc

if (errorMsg.lengt h > 0) {
alert(
'Please correct the following' +
' errors before continuing:\n\n- ' +
errorMsg.join(' \n- ')
);
if (firstFieldToFo cus) {
firstFieldToFoc us.focus();
}
}

The code also places the cursor in the first of the input boxes containing errors. This behaviour
is optional, your users may not appreciate the form scrolling almost to the top, they may prefer
to fix the problems in their own order.

--
Grant Wagner <gw*****@agrico reunited.com>
comp.lang.javas cript FAQ - http://jibbering.com/faq
Jul 23 '05 #4

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

Similar topics

1
37223
by: Maria | last post by:
Hello we got a script automatically generated to populate a table that belongs to a partition table, then while executing we get this error message: "DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: 12-14-2004 17:45:55 SQL0204N "TABLE_NAME" is an undefined name.
2
1318
by: Jon | last post by:
Hi all I know this is not the preferred newsgroup, but you people are great with SQL MS ACCESS, VISUAL BASIC6 Hope you can see past my table, string definitions (Swedish), just ask otherwise Having some problem with a SQL statement I need to be able to run strSQL3, but I get an error about sum and that I
5
1531
by: hamishd | last post by:
Hello, In my application I create some large vectors to hold data. For example: std::vector<DataItemClass*MyData; DataItemClass * DataItem; for(i=0;i<SomeLargeLimit;i++){ DataItem = new DataltemClass;
1
6106
by: Billy | last post by:
I do a SELECT * from table command in an ASP page to build a text file out on our server, but the export is not to allow a field name rows of records. The first thing I get is a row with all the field names. Why do these come in if they are not part of the table records? How do I eliminate this from being produced? Here's the ASP code.... <html> <head>
0
2441
by: PeterA | last post by:
I have a Windows PC connecting to ISeries with ODBC. The windows PC uses various SQL statements to connect to DB2 and download/upload data. Data downloads/uploads appear to be OK and I can't see any data errors but I'm getting this message in the job log: Token <END-OF-STATEMENT> was not valid. Valid tokens: + - AS <IDENTIFIER>. Message ID . . . . . . : SQL0104 Severity . . . . . . . : 30 Message type . . . . . : Diagnostic ...
1
1588
by: patriciashoe | last post by:
Everything I read indicates the following statement should work. What happens is that any field after the where clause gets treated as a parameter by Access. Even if I supply the data the query fails. Any ideas? Thanks, Patti UPDATE teacherresources SET teacherresources.Strudent_enroll = strudent_enroll/(SELECT sum(enroll_data) FROM enrollment WHERE teacherresources.trSchool_id = enrollment.erSchool_id and year='2007-2008')*(SELECT...
2
1347
by: Lebbsy | last post by:
I have a datasheet form that on opening I want to select only the records whose Decision field value is "Recommend". I have the following SQL statement so far but it gives me the "cannot execute select query" error. strSQL = "SELECT IdentityNumber, Ministry, Surname, Designation, QualificationCategory, Qualification, SubmissionDate" _ & " FROM " _ & " WHERE = 'Recommend';" dbs.Execute (strSQL) Debug.Print strSQL...
1
1475
Fary4u
by: Fary4u | last post by:
Hi, I'm attempting to update a record via the recordset.update method, However, the recordset object is defined and accesses the correct record that I want to update, as I can retrieve field values from the record. The open string for the recordset that I'm using should allow changes: ors.open "Select * from products where productname='"&request("txtname")&"'",ocon1,Adopendynamic,Adlockoptimistic
5
1859
by: Mr Hero | last post by:
I need assitance with my IIF statement. IIf(!!="1",True,IIf(!!="2",False,IIf(!!="3",,))) I have a column in my table that stores values from a check box in my form. I have a form that has a option group in it, and it has 3 buttons to select from. Depending on the value, you can get 1, 2 or 3 as your value; hence my IIF statement. Selection "1" will allow my report to filter my data for only checked boxes to display on my report....
0
9287
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
10046
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9857
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
9722
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
8723
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...
0
6542
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5155
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5318
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2677
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.