一旦失去焦点,如何动态更正TextBox的输入验证?

时间:2014-02-25 07:34:07

标签: c# regex wpf windows-phone-8 textbox

我对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:";
        }
    }

2 个答案:

答案 0 :(得分:3)

问题在于查看文本框是否包含空字符串,例如:

... || lastNameTB.Text.Contains("") || ...
... || firstNameTB.Text.Contains("") || ...

因为这些总是评估为true - 您会得到您描述的行为 要解决此问题 - 只需从if语句中删除这些条件。

答案 1 :(得分:2)

您可以使用String.Empty检查String是否为空:

if (string.IsNullOrWhiteSpace(lastNameTB.Text) ||
    lastNameTB.Text == String.Empty || 
    !Regex.IsMatch(lastNameTB.Text, @"^[A-Z]{1}[a-z]+$"))
{

}