我有一个CustomValidator,可以检查文本框中输入的文本是否与数据库中的某些字段匹配。这一切以前都很好用,但从那以后我修改了我的页面,它不再工作了。我不认为我改变了任何会影响这一点的东西,但很明显我改变了。我的所有其他验证器(必需的字段验证器)都工作正常,但我的CustomValidator没有响应。
所以不管怎样,下面是我的代码:
CustomValidator:
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="txtCoursePrefix" ErrorMessage="Course number is already taken."></asp:CustomValidator>VB代码幕后:
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
'Checking for duplicate course numbers
'get values
Dim checkPrefix = txtCoursePrefix.Text
Dim checkNum = txtCourseNum.Text
'db connectivity
Dim myConn As New OleDbConnection
myConn.ConnectionString = AccessDataSource2.ConnectionString
myConn.Open()
'select records
Dim mySelect As New OleDbCommand("SELECT 1 FROM tableCourse WHERE prefix=? AND course_number=?", myConn)
mySelect.Parameters.AddWithValue("@checkPrefix", checkPrefix)
mySelect.Parameters.AddWithValue("@checkNum", checkNum)
'execute(Command)
Dim myValue = mySelect.ExecuteScalar()
'check if record exists
If myValue IsNot Nothing Then
CustomValidator1.SetFocusOnError = True
args.IsValid = False
End If
End Sub在CustomValidator1.SetFocusOnError = True和args.IsValid = False之前,一切都在进行。我已经测试了If语句,它工作正常,它返回true,我放在里面的任何东西都会执行。
发布于 2012-07-27 17:46:09
使用customvalidators时需要注意的事项:
如果您正在使用ValidationGroup进行验证,不要忘记将其添加到您的CustomValidator中。
设置ControlToValidate属性。
除非设置了ValidateEmptyText=true,否则CustomValidator控件在ControlToValidate控件为空时从不激发。
使用ClientValidationFunction="customClientValidationFunction"时,请使用以下签名:
function customClientValidationFunction(sender, arguments) {
arguments.IsValid = true; //validation goes here
}发布于 2012-09-12 19:55:05
您应该在CustomValidator上设置属性ValidateEmptyText="true"。在这种情况下,将始终调用客户端和服务器函数。
它为我解决了这个问题。
发布于 2012-07-01 09:42:08
如果处理程序被调用,并且您成功地将args.IsValid设置为false,那么它所做的就是将Page.IsValid设置为false。但不幸的是,这并不能阻止表单被提交。您需要做的是检查处理表单提交的代码中的Page.IsValid属性,就像在提交按钮处理程序中一样。
因此,除了您发布的代码之外,请确保您的提交处理程序(C#示例)具有类似于以下内容的内容:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
{
// by simply returning, the error message for the CustomValidator will be displayed
return;
}
// do processing for valid form here
}https://stackoverflow.com/questions/6163336
复制相似问题