Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CustomValidator not working

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.

like image 733
Sara Avatar asked Dec 16 '22 13:12

Sara


2 Answers

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
}
like image 102
Peter Avatar answered Jan 01 '23 17:01

Peter


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.

like image 43
Splendid Avatar answered Jan 01 '23 17:01

Splendid