验证用户的输入

本文关键字:输入 用户 验证 | 更新日期: 2023-09-27 17:52:36

我有3个文本框:textbox1, textbox2, textbox3。用户只允许在一个文本框中填写信息。

private string determineSearchParameter()
{
    //Execute statements if ALL textboxes are empty
    if (string.IsNullOrWhiteSpace(textbox1.Text) && string.IsNullOrWhiteSpace(textbox2.Text) &&
        string.IsNullOrWhiteSpace(textbox3.Text))
    {
        return "Please Enter a Search Parameter";
    }
    //Execute all fields have an input
    if (!string.IsNullOrEmpty(textbox2.Text) && !string.IsNullOrWhiteSpace(textbox1.Text) &&
        !string.IsNullOrWhiteSpace(textbox3.Text))
    {
        return "Please only enter one Criteria";
    }
    //Execute statments if multiple textboxes have values
    if (!string.IsNullOrWhiteSpace(textbox3.Text) && !string.IsNullOrWhiteSpace(textbox1.Text))
    {
        return "Please only enter one Criteria";
    }
    if (!string.IsNullOrWhiteSpace(textbox3.Text) && !string.IsNullOrWhiteSpace(textbox2.Text))
    {
        return "Please only enter one Criteria";
    }
    if (!string.IsNullOrWhiteSpace(textbox1.Text) && !string.IsNullOrWhiteSpace(textbox2.Text))
    {
        return "Please only enter one Criteria";
    }
    if (!string.IsNullOrWhiteSpace(textbox1.Text) && string.IsNullOrEmpty(textbox2.Text) &&
        string.IsNullOrEmpty(textbox3.Text))
    {
        return "Something else";
    }
    if (!string.IsNullOrWhiteSpace(textbox2.Text) && string.IsNullOrEmpty(textbox1.Text) &&
        string.IsNullOrEmpty(textbox3.Text))
    {
        return "Something there";
    }
    if (!string.IsNullOrWhiteSpace(textbox3.Text) && string.IsNullOrEmpty(textbox1.Text) &&
        string.IsNullOrEmpty(textbox2.Text))
    {
        return "Something here";
    }
    return "";
}

是否有其他方法来验证这些文本框?

验证用户的输入

如何:

var state1 = string.IsNullOrWhiteSpace(textbox1.Text);
var state2 = string.IsNullOrWhiteSpace(textbox2.Text);
var state3 = string.IsNullOrWhiteSpace(textbox3.Text);
if (!(state1 || state2 || state3))
{
    return "Please Enter a Search Parameter";
}
if (!(state1 ^ state2 ^ state3))
{
    return "Please only enter one Criteria";
}
if (state1)
{
    return "Something else";
}
if (state2)
{
    return "Something there";
}
return "Something here";