Skip to main content
 首页 » 编程设计

c#之使用正则表达式和 bool 值清理输入

2024年02月27日36zhenyulu

我正在使用 Regex 验证电子邮件、密码和用户名输入是否合法。它没有验证。用户可以输入他们想要的任何内容,它会进入我的数据库。

为了执行//function,我希望所有的 bool 值都为真。

    private void bunifuFlatButton2_Click(object sender, EventArgs e) 
    { 
        string username = textBox1.Text; 
        bool IsRealUser = Regex.IsMatch(username, @"\A(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)\Z"); 
        string password = textBox2.Text; 
        bool IsRealPass = Regex.IsMatch(password, @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$"); 
        string email = textBox4.Text; 
        bool IsRealEmail = Regex.IsMatch(email, @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"); 
 
        if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "") 
        { 
            System.Windows.Forms.MessageBox.Show("Fill out the required forms!"); 
            return; 
        } 
        else if (textBox2.Text != textBox3.Text) 
        { 
            System.Windows.Forms.MessageBox.Show("Your passwords are not matching"); 
        } 
 
        else if (IsRealPass || IsRealUser || IsRealEmail) //I want all these inputs to be true in order to execute //function. 
        { 
             //function 
        } 

请您参考如下方法:

如所写,如果任何测试为真,该 block 将被执行。

    else if (IsRealPass || IsRealUser || IsRealEmail) 
    { 
         //function 
    } 

您需要 && 以便所有测试条件都必须为真才能执行该 block 。

    else if (IsRealPass && IsRealUser && IsRealEmail) 
    { 
         //function 
    }