我对我的if语句感到困惑,该语句说如果文本框为空,具有空格,空字符串,包含特定字符或具有正则表达式字符,它将验证为正确。但相反,当我输入文本时,它会验证为不正确,然后按照 if 语句的要求失去焦点传递。我在这里做错了什么?我注意到添加一个 if(!(..)) 会让它以相反的方式工作,但这不是正确的逻辑,我很困惑。
// firstNameTB Textbox to dynamically check validation
private void firstNameTB_LostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(firstNameTB.Text) || firstNameTB.Text == "" || firstNameTB.Text.Contains("") || !Regex.IsMatch(firstNameTB.Text, @"^[A-Z]{1}[a-z]+$"))
{
firstNameTBL.Text = "First Name: *";
firstNameTBL.Foreground = new SolidColorBrush(Colors.Red);
firstNameTBL.FontWeight = FontWeights.Bold;
}
else
{
// set back to default layout
this.firstNameTBL.ClearValue(TextBlock.ForegroundProperty);
this.firstNameTBL.ClearValue(TextBlock.FontWeightProperty);
this.firstNameTBL.Text = "First Name:";
}
}
// lastNameTB Textbox to dynamically check validation
private void lastNameTB_LostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(lastNameTB.Text) || lastNameTB.Text == "" || lastNameTB.Text.Contains("") || !Regex.IsMatch(lastNameTB.Text, @"^[A-Z]{1}[a-z]+$"))
{
lastNameTBL.Text = "Last Name: *";
lastNameTBL.Foreground = new SolidColorBrush(Colors.Red);
lastNameTBL.FontWeight = FontWeights.Bold;
}
else
{
// set back to default layout
this.lastNameTBL.ClearValue(TextBlock.ForegroundProperty);
this.lastNameTBL.ClearValue(TextBlock.FontWeightProperty);
this.lastNameTBL.Text = "Last Name:";
}
}
// emailAddressTB Textbox to dynamically check validation
private void emailAddressTB_LostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(emailAddressTB.Text) || emailAddressTB.Text == "" || !(emailAddressTB.Text.Contains("@") && emailAddressTB.Text.Contains(".")))
{
emailAddressTBL.Text = "Email Address: *";
emailAddressTBL.Foreground = new SolidColorBrush(Colors.Red);
emailAddressTBL.FontWeight = FontWeights.Bold;
}
else
{
// set back to default layout
this.emailAddressTBL.ClearValue(TextBlock.ForegroundProperty);
this.emailAddressTBL.ClearValue(TextBlock.FontWeightProperty);
this.emailAddressTBL.Text = "Email Address:";
}
}
问题在于查看文本框是否包含空字符串,例如:
... || lastNameTB.Text.Contains("") || ...
... || firstNameTB.Text.Contains("") || ...
因为这些总是评估为true
- 你得到你描述的行为。
要解决此问题 - 只需从 if 语句中删除这些条件即可。
您可以使用
String.Empty
来检查字符串是否为空:
if (string.IsNullOrWhiteSpace(lastNameTB.Text) ||
lastNameTB.Text == String.Empty ||
!Regex.IsMatch(lastNameTB.Text, @"^[A-Z]{1}[a-z]+$"))
{
}