-2

I want to validate two masked textboxes. At least one of them needs to have a value. I have the following code

bool validatePhoneNumbers() 
{
     bool valid = false;
     if (!txtClientFax.MaskCompleted || !txtClientMobile.MaskCompleted) 
     {
          MessageBox.Show("Please enter telephone or mobile number under Client Section");
     }
     return valid;
}

If i test separately without using || it works. I want to check for both masked textboxes all at once

NASSER
  • 5,900
  • 7
  • 38
  • 57
lucy
  • 7
  • 1
  • You don't assign valid to true – netaholic Aug 31 '15 at 09:57
  • 1
    According to that logic, *both* of them must have a value. – David Aug 31 '15 at 09:59
  • There is nothing special about this code, and it's not related to MaskedTextBoxes. You're just comparing booleans. Boolean logic is relatively simple. Write out _exactly_ what you want to happen and explain what "doesn't work". Also, please don't use Hungarian notation (`txt` prefix). – CodeCaster Aug 31 '15 at 10:02
  • I want to compare if either of the textboxes has a value – lucy Aug 31 '15 at 10:05
  • No, you don't. You want to check whether both textboxes _don't_ have a value. – CodeCaster Aug 31 '15 at 10:06

2 Answers2

1

Boolean logic is fundamental and simple. Prevent double negatives and write out your input. After that, you can simplify and reduce the expressions.

bool faxEntered = txtClientFax.MaskCompleted;
bool mobileEntered = txtClientMobile.MaskCompleted;

bool neitherEntered = !faxEntered && !mobileEntered;

if (neitherEntered)
{
    // show alert
}

Above if() checks whether both textboxes don't have a value entered. If either has one, the neitherEntered will be false.

You can reverse it:

bool eitherEntered = faxEntered || mobileEntered;

if (!eitherEntered)
{
    // show alert
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
0
bool validatePhoneNumbers() 
{
 bool valid = false;
 if (!(txtClientFax.MaskCompleted || txtClientMobile.MaskCompleted))
 {
      MessageBox.Show("Please enter telephone or mobile number under Client Section");
 }
 return valid;
}
andy
  • 5,979
  • 2
  • 27
  • 49