表单中的有效数据

本文关键字:有效数 数据 有效 表单 | 更新日期: 2023-09-27 18:26:55

无论我输入什么,我的数据总是正确的。我从一个文本框中获取数据,用户可以在其中输入数据。我做错了什么?Utility.ValidName和Utility.Email返回true或false。

检查

string username = null;
string email = null;
username = textBox1.Text;
email = textBox2.Text;
bool vusernam = false;
bool vemail = false;
vusernam = Utility.ValidName ( username );
vemail = Utility.ValidEmail ( email );
if ( vusernam == true && vemail == true )
{
    Utility.WelcomeMessage ( string.Format ( "Hello {0}'nEMail: {1}'nWelcome!" , username , email ) );
    secondForm.Show ( );
    this.Hide ( );
}
else
{
    MessageBox.Show ( "Please Enter a Username and Email Adress!" );
}

有效的用户名和电子邮件

 public static bool ValidEmail ( string email )
    {
        string strTest = email;
        Regex pattern = new Regex ( @"(?<name>'S+)@(?<domain>'S+)" );
        Match match = pattern.Match ( strTest );
        if ( String.IsNullOrEmpty ( email ) || !match.Success )
        {
            Console.Write ( "'nInvalid Email!" );
        }
        return true;
    }
    public static bool ValidName ( string name )
    {
        string strTest = name;

        if ( String.IsNullOrEmpty ( name ) )
        {

            Console.Write ( "'nInvalid Name!" );

        }
        return true;
    }

表单中的有效数据

不管怎样,您总是返回true。

在Console.Write之后添加一个return false。简单地输出一条错误消息不会导致验证失败。

public static bool ValidName ( string name )
{
    string strTest = name;
    if ( String.IsNullOrEmpty ( name ) )
    {
        Console.Write ( "'nInvalid Name!" );
        return false;
    }
    return true;
}

旁注:

if ( vusernam == true && vemail == true )

可以简化为简单的

if(vusernam && vemail)

并且CCD_ 1似乎根本没有任何作用。

方法总是返回true的原因是因为您只返回true。

public static bool ValidEmail (string email)
{
    Regex pattern = new Regex( @"(?<name>'S+)@(?<domain>'S+)" );
    Match match = pattern.Match(email);
    return !String.IsNullOrEmpty(email) && match.Success
}
public static bool ValidName (string name)
{
    return !String.IsNullOrEmpty(name);
}