I'm still trying to get my validation to work correctly. So far if a user enters in a Salesman Code that exists in the database it displays the error message when tabbing off the field. The Salesman Code field is also required so I can't get this validator to work either with the customer validator that checks duplicates. What I am looking for is when a user does not enter a Salesman Code for the error to appear and not let the user submit the form. If the user enters a Salesman Code that exists in the database the error message will be displayed and the user should not be allowed to submit the form. Any help or examples would be appreciated. Below is my code that I have using VB.
Below is my aspx page:
<%@ Page Language="VB" %>
<%@ Register TagPrefix="custom" Namespace="myControls" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
''' Validation function that is called on both the client and server
Protected Sub AjaxValidator1_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
If Salesman_CodeExists(args.Value) Then
args.IsValid = False
Else
args.IsValid = True
Me.btnSubmit.Attributes.Add("onclick", "alert('Please try a different Salesman Code!');return false;")
End If
End Sub
''' <summary>
''' Returns true when user name already exists
''' in Users database table
''' </summary>
Private Function Salesman_CodeExists(ByVal Salesman_Code As String) As Boolean
Dim conString As String = WebConfigurationManager.ConnectionStrings("PennerConnectionString").ConnectionString
Dim con As New SqlConnection(conString)
Dim cmd As New SqlCommand("SELECT COUNT(*) FROM tblSalesman WHERE Salesman_Code=@Salesman_Code", con)
cmd.Parameters.AddWithValue("@Salesman_Code", Salesman_Code)
Dim result As Boolean = False
Using con
con.Open()
Dim count As Integer = CType(cmd.ExecuteScalar(), Integer)
If count > 0 Then
result = True
Else
End If
End Using
Return result
End Function
''' Insert new user name to Users database table
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim conString As String = WebConfigurationManager.ConnectionStrings("PennerConnectionString").ConnectionString
Dim con As New SqlConnection(conString)
Dim cmd As New SqlCommand("INSERT tblSalesman (Salesman_Code,Salesman_LastName) VALUES (@Salesman_Code,@Salesman_LastName)", con)
cmd.Parameters.AddWithValue("@Salesman_Code", txtSalesman_Code.Text)
cmd.Parameters.AddWithValue("@Salesman_LastName", txtSalesman_LastName.Text)
Using con
con.Open()
cmd.ExecuteNonQuery()
End Using
txtSalesman_Code.Text = String.Empty
txtSalesman_LastName.Text = String.Empty
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show AjaxValidator</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label
id="lblSalesman_Code"
Text="Salesman Code:"
AssociatedControlID="txtSalesman_Code"
Runat="server" />
<asp:TextBox
id="txtSalesman_Code"
Runat="server" />
<custom:AjaxValidator
id="AjaxValidator1"
ControlToValidate="txtSalesman_Code"
Text="User name already taken!"
OnServerValidate="AjaxValidator1_ServerValidate"
Runat="server" />
<br /><br />
<asp:Label
id="lblSalesman_LastName"
Text="Last Name:"
AssociatedControlID="txtSalesman_LastName"
Runat="server" />
<asp:TextBox
id="txtSalesman_LastName"
Runat="server" />
<br /><br />
<asp:Button
id="btnSubmit"
Text="Submit"
Runat="server" OnClick="btnSubmit_Click" />
</div>
</form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Register TagPrefix="custom" Namespace="myControls" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
''' Validation function that is called on both the client and server
Protected Sub AjaxValidator1_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
If Salesman_CodeExists(args.Value) Then
args.IsValid = False
Else
args.IsValid = True
Me.btnSubmit.Attributes.Add("onclick", "alert('Please try a different Salesman Code!');return false;")
End If
End Sub
''' <summary>
''' Returns true when user name already exists
''' in Users database table
''' </summary>
Private Function Salesman_CodeExists(ByVal Salesman_Code As String) As Boolean
Dim conString As String = WebConfigurationManager.ConnectionStrings("PennerConnectionString").ConnectionString
Dim con As New SqlConnection(conString)
Dim cmd As New SqlCommand("SELECT COUNT(*) FROM tblSalesman WHERE Salesman_Code=@Salesman_Code", con)
cmd.Parameters.AddWithValue("@Salesman_Code", Salesman_Code)
Dim result As Boolean = False
Using con
con.Open()
Dim count As Integer = CType(cmd.ExecuteScalar(), Integer)
If count > 0 Then
result = True
Else
End If
End Using
Return result
End Function
''' Insert new user name to Users database table
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim conString As String = WebConfigurationManager.ConnectionStrings("PennerConnectionString").ConnectionString
Dim con As New SqlConnection(conString)
Dim cmd As New SqlCommand("INSERT tblSalesman (Salesman_Code,Salesman_LastName) VALUES (@Salesman_Code,@Salesman_LastName)", con)
cmd.Parameters.AddWithValue("@Salesman_Code", txtSalesman_Code.Text)
cmd.Parameters.AddWithValue("@Salesman_LastName", txtSalesman_LastName.Text)
Using con
con.Open()
cmd.ExecuteNonQuery()
End Using
txtSalesman_Code.Text = String.Empty
txtSalesman_LastName.Text = String.Empty
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show AjaxValidator</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label
id="lblSalesman_Code"
Text="Salesman Code:"
AssociatedControlID="txtSalesman_Code"
Runat="server" />
<asp:TextBox
id="txtSalesman_Code"
Runat="server" />
<custom:AjaxValidator
id="AjaxValidator1"
ControlToValidate="txtSalesman_Code"
Text="User name already taken!"
OnServerValidate="AjaxValidator1_ServerValidate"
Runat="server" />
<br /><br />
<asp:Label
id="lblSalesman_LastName"
Text="Last Name:"
AssociatedControlID="txtSalesman_LastName"
Runat="server" />
<asp:TextBox
id="txtSalesman_LastName"
Runat="server" />
<br /><br />
<asp:Button
id="btnSubmit"
Text="Submit"
Runat="server" OnClick="btnSubmit_Click" />
</div>
</form>
</body>
</html>
Below is my AjaxValidator.vb file:
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Namespace myControls
''' <summary>
''' Enables you to perform custom validation on both the client and server
''' </summary>
Public Class AjaxValidator
Inherits BaseValidator
Implements ICallbackEventHandler
Public Event ServerValidate As ServerValidateEventHandler
Dim _controlToValidateValue As String
Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
Dim eventRef As String = Page.ClientScript.GetCallbackEventReference(Me, "", "", "")
' Register include file
Dim includeScript As String = Page.ResolveClientUrl("~/js/AjaxValidator.js")
Page.ClientScript.RegisterClientScriptInclude("AjaxValidator", includeScript)
' Register startup script
Dim startupScript As String = String.Format("document.getElementById('{0}').evaluationfunction = 'AjaxValidatorEvaluateIsValid'", Me.ClientID)
Page.ClientScript.RegisterStartupScript(Me.GetType(), "AjaxValidator", startupScript, True)
MyBase.OnPreRender(e)
End Sub
''' <summary>
''' Only do the AJAX call on browsers that support it
''' </summary>
Protected Overrides Function DetermineRenderUplevel() As Boolean
Return Context.Request.Browser.SupportsCallback
End Function
''' <summary>
''' Server method called by client AJAX call
''' </summary>
Public Function GetCallbackResult() As String Implements ICallbackEventHandler.GetCallbackResult
Return ExecuteValidationFunction(_controlToValidateValue).ToString()
End Function
''' <summary>
''' Return callback result to client
''' </summary>
Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements ICallbackEventHandler.RaiseCallbackEvent
_controlToValidateValue = eventArgument
End Sub
''' <summary>
''' Server-side method for validation
''' </summary>
Protected Overrides Function EvaluateIsValid() As Boolean
Dim controlToValidateValue As String = Me.GetControlValidationValue(Me.ControlToValidate)
Return ExecuteValidationFunction(controlToValidateValue)
End Function
''' <summary>
''' Performs the validation for both server and client
''' </summary>
Private Function ExecuteValidationFunction(ByVal controlToValidateValue As String) As Boolean
Dim args As New ServerValidateEventArgs(controlToValidateValue, Me.IsValid)
RaiseEvent ServerValidate(Me, args)
Return args.IsValid
End Function
End Class
End Namespace
Below is my AjaxValidator.js file:
// Performs AJAX call back to server
function AjaxValidatorEvaluateIsValid(val) {
var value = ValidatorGetValue(val.controltovalidate);
WebForm_DoCallback(val.id, value, AjaxValidatorResult, val,
AjaxValidatorError, true);
return true;
}
// Called when result is returned from server
function AjaxValidatorResult(returnValue, context) {
if (returnValue == 'True')
context.isvalid = true;
else
context.isvalid = false;
ValidatorUpdateDisplay(context);
}
// If there is an error, show it
function AjaxValidatorError(message) {
alert('Error: ' + message);
}