我正在努力寻找一种合适或优雅的方式来处理服务器端代码中的验证。目前我正在使用 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;
}
问题是随着检查更多复选框(换句话说,查看更多上下文),验证变得复杂。
我正在考虑将它作为一种上帝方法来提供所有验证,无论页面中的哪个按钮调用它(我对这种方法的任何建议/批评持开放态度)。
- 页面是从头开始制作的,并且经常添加新功能/控件/验证。
笔记:
我知道Requiredfield 验证器,由于一些复杂性,我在这里避免使用它。