I have a CustomValidator that checks if text entered in textboxes matches certain fields in a database. This was all working great before, but I have modified my page quite a bit since then and it is no longer working. I didn't think I changed anything that would affect this, but apparently I did. All my other validators (required field validators) are working correctly, but my CustomValidator isn't responding.
So anyway, here is my code:
CustomValidator:
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="txtCoursePrefix" ErrorMessage="Course number is already taken."></asp:CustomValidator>
VB codebehind:
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
Everything is working up until CustomValidator1.SetFocusOnError = True and args.IsValid = False. I have tested the If statement and it's working correctly, it returns true and anything else I put inside of it executes.
Things you should know when using customvalidators:
If you are validating using a ValidationGroup, don't forget to add it to your CustomValidator.
Set the ControlToValidate property.
A CustomValidator control never fires when the ControlToValidate control is empty unless you set ValidateEmptyText=true.
When using ClientValidationFunction="customClientValidationFunction" use the following signature: 
function customClientValidationFunction(sender, arguments) {
   arguments.IsValid = true; //validation goes here
}
                        You should set the property ValidateEmptyText="true" on the CustomValidator. The client and server functions will always be called in that case.
It solved the problem for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With