Monday, March 26, 2012

Validation Control

Hi All

I have an editable DataGrid, when user is in Update mode than I want to check the value entered, I have a requiredFieldValidator on the textBox. I want to check if the same entry already exist in the database than user should not allowed to proceed further. Do I need to write a custom validator for this but this is not client side validaion?

Given the fact that you need to query the database in order to validate, yes you do need a custom validator and it can't be a client side one.
Would you please help me in writing one as I've never worked with this validation control.

I tried to write a Custom validator but its not working, but requiredField Validator is working.

txt is the TextBox to be validated.

<EditItemTemplate>
<asp:TextBox ID="txt" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"CustName") %>' >
</asp:TextBox>
<asp:RequiredFieldValidator ID="rfvTxt" Runat="server" Display="Dynamic" ControlToValidate="txt"
ErrorMessage="Enter Category"></asp:RequiredFieldValidator>
<asp:CustomValidator id="CustomValidator1" runat="server" OnServerValidate="CustomValidator1_ServerValidate" ErrorMessage="Entry already exist" ControlToValidate="txt"></asp:CustomValidator>
</EditItemTemplate>

Sub CustomValidator1_ServerValidate(ByVal source As System.Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
objCmd = New SqlCommand("Select CustName from table1 where typeName = '" & args.Value & "'", objConn)
objConn.Open()
objDR = objCmd.ExecuteReader()
If objDR.HasRows = True Then
args.IsValid = False
Else
args.IsValid = True
End If
objConn.Close()
End Sub


The above code returns args.IsValid=False-If value entered in TextBox already exist in the database. But the problem is it continutes to update instead of showing the error message.


Yes mate, you are going down the right path. The catch is that when using the validator controls you should always check the property Page.IsValid before doing any after postback processing. You probably didn't stumble upon this issue before because most out-of-the-box validators perform the validation on the client side so the postback is supressed in case the validation fails. That is the ideal situation, however in certain cases (such as the custom validator you are developing) the postback is necessary to validate, and therefore you should make a habit of checking the Page.IsValid before doing anything if you are using validators. I hope this makes sense.

No comments:

Post a Comment