0

I am working on a custom validator that needs to fail if either an email address or username haven't changed. Essentially if one of the string comparisons are true then it will pass the validation. I know I'm overlooking something simple. Here is what I have so far:

bool emailChanged = Domain.Validation.ItemsHaveChanged(txtEmailAddress.Text, emailAddress);
bool userNameChanged = Domain.Validation.ItemsHaveChanged(txtUserName.Text, userName);

// make sure at least the email or username has changed.
if (!emailChanged || !userNameChanged)
{
     args.IsValid = false;
     cvAccountChange.ErrorMessage = "There haven't been any changes to the account.";
 }

Here is the method ItemsHaveChanged

public static bool ItemsHaveChanged(string param1, string param2)
{
    return string.Compare(param1.Trim(), param2.Trim()) != 0;
}
4

2 回答 2

4

您正在寻找逻辑 AND 运算符 ( &&):

if (!emailChanged && !userNameChanged)
{
     args.IsValid = false;
     cvAccountChange.ErrorMessage = "There haven't been any changes to the account.";
}
于 2013-07-20T16:37:13.853 回答
1

就个人而言,我会避免 brobdingnagian 条件,只是这样做:

if (emailChanged || usernameChanged) {
    // everything is fine
    return;
}

// neither changed
args.IsValid = false;
...

也就是说,假设您可以从该方法中提前返回。(此外,您始终可以将剪断的代码提取到单独的代码中。)

或者,您可以通过以下方式避免提前返回和复杂的表达式:

var emailUnchanged = !ItemsHaveChanged(...);
var usernameUnchanged = !ItemsHaveChanged(...);

if (emailUnchanged || usernameUnchanged) {
    // neither changed
    args.IsValid = false;
    ...
}
于 2013-07-20T16:40:27.850 回答