您可以对照数据库来验证用户输入,以确保用户输入的值可以识别。为此,您必须在 CustomValidator 控件中编写代码,在数据库中查找数据匹配项。
1、将 CustomValidator 控件添加到页中并设置下列属性:
属性 | 说明 |
正在验证的控件的 ID。 | |
这些属性指定验证失败时要显示的错误的文本和位置。 |
2、为 CustomValidator 控件的 ServerValidate 事件创建一个事件处理程序。在事件处理程序中,添加代码查找数据库并对照数据集检查用户输入。
说明: 如果用户将控件保留为空白,则此控件将通过比较验证。若要强制用户输入值,则还要添加 RequiredFieldValidator 控件。
3、在 ASP.NET 网页代码中添加测试,以检查有效性。
下面的代码示例演示如何通过在数据库表中进行查询来验证用户的输入。在此例中,将对照表中存储的电子邮件地址对用户输入的电子邮件地址进行验证。自定义验证逻辑将依次通过表中的各行,该表是页中可以使用的数据集的一部分。
private void CustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
{
DataView dv;
DataSet dataSet11 = new DataSet();
dv = dataSet11.Tables[0].DefaultView;
string txtEmail;
args.IsValid = false; // Assume False
// Loop through table and compare each record against user's entry
foreach (DataRowView datarow in dv)
{
// Extract e-mail address from the current row
txtEmail = datarow["Alias "].ToString();
// Compare e-mail address against user's entry
if (txtEmail == args.Value)
{
args.IsValid = true;
}
}
}