GUI 控制验证模式

本文关键字:模式 验证 控制 GUI | 更新日期: 2023-09-27 18:30:59

我正在努力寻找一种合适或优雅的方式来处理服务器端代码中的验证。目前我正在使用 asp.net 网站,但是我希望有一种同样适用于MVC的模式。

我发布一个示例/伪代码纯粹是为了描述问题,实际代码差异很大,而且非常复杂:

标记代码如下所示:

    <asp:CheckBoxList ID="CheckBoxList1" runat="server">
        <asp:ListItem>Item1</asp:ListItem>
        <asp:ListItem>Item2</asp:ListItem>
        <asp:ListItem>Item3</asp:ListItem>
    </asp:CheckBoxList>
    <asp:CheckBoxList ID="CheckBoxList2" runat="server">
        <asp:ListItem>Item4</asp:ListItem>
        <asp:ListItem>Item5</asp:ListItem>
        <asp:ListItem>Item6</asp:ListItem>
    </asp:CheckBoxList>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />

代码隐藏如下所示:

protected void Button1_Click(object sender, EventArgs e)
{
    if (ValidatePage()) {
        //call business layer and do some operation.
    }
}
bool ValidatePage()
{
    int visibility = GetVisibility();
    switch (visibility)
    {
        case 0: //TextBox1.Text can not be empty
        //in case it is found to be empty then return false and print the message in web page
        case 1: //TextBox1.Text can not be empty
        //in case it is found to be empty then return false and print the message in web page
        case 2: // both of textbox1 and textbox2 should not be empty
        //in case they are found to be empty then return false and print the message in web page
    }
    //return true or false as per the above validations
}
int GetVisibility()
{
    //if page is redirected from page1 then return 1
    //if page is redirected from page2 then return 2
    //if page is directly open from homepage then return 0
    return 0;
}

  1. 问题是验证变得复杂,因为更多的复选框是已检查(换句话说,查看更多上下文)。

  2. 我在想 制作为上帝的方法,无论如何都会提供所有验证 页面中的哪个按钮正在调用它(我对任何 对这种方法的建议/批评)。

  3. 页面是从头开始制作的,新功能/控件/验证是经常添加。

注意:

我知道必填字段验证器,由于一些复杂性,我在这里避免它。

GUI 控制验证模式

我会创建一个类,其中包含对相关控件的引用,以及一个Validate()方法(可以在子类中实现或作为lambda传入)。然后,我将实例保留在一个集合中,我将迭代该集合以调用每个Validate()