Search code examples
c#maskedtextbox

C# || operator not working for masked textboxes


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


Solution

  • 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
    }