A CustomValidator Problem, I don't understand the logic

A

antonyliu2002

The full code is pasted below. It looks scarily long, but it's pretty
simple. It is adapted from a sample code at MSDN.

If you run it, and check it out from your browser, you'll see:

CustomValidator ServerValidate Example
Enter an even number:
[_________________]

Zip: [______________]

[Validate!]

I want to check if the number is valid only if the zip is valid.
That's why I have

If vldZip.IsValid Then

'Check if the number entered is even.

End If

But, the number is checked even if the zip is invalid. Try "asdf" for
the Zip and 13 for the even number, and you'll see what I meant.

I don't understand this, my logic in the code seems to be correct.

Please help. Thanks a lot!

********The fully workable code below************

<%@ Page Language="VB" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script runat="server">
Sub ValidateBtn_OnClick(sender As Object, e As EventArgs)
If vldZip.IsValid Then
Message.Text = "Zip is valid."
Else
Message.Text = "Zip is not valid!"
End If

End Sub

Sub ServerValidation(source As Object, args As
ServerValidateEventArgs)
If vldZip.IsValid() Then
Try
' Test whether the value entered into the text box is even.
Dim num As Integer = Integer.Parse(args.Value)
args.IsValid = ((num mod 2) = 0)
Catch ex As Exception
args.IsValid = false
End Try
End If
End Sub
</script>

<title>Custom Validator Test</title></head>
<body>
<form runat="server">
<h3>CustomValidator ServerValidate Example</h3>
<asp:Label id="Message"
Text="Enter an even number:"
Font-Name="Verdana"
Font-Size="10pt"
runat="server" />

<p>
<asp:TextBox id="Text1"
runat="server" />

<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
Display="Static"
ErrorMessage="Not an even number!"
ForeColor="green"
Font-Name="verdana"
Font-Size="10pt"
OnServerValidate="ServerValidation"
runat="server"/>
<p>
Zip:
<asp:RegularExpressionValidator
ControlToValidate="txtZip"
Display="Dynamic"
EnableClientScript="false"
ErrorMessage="Invalid Zip! <br />"
ID="vldZip"
runat="server"
ValidationExpression="[0-9]{5}" />

<asp:TextBox ID="txtZip"
Columns="5"
MaxLength="5"
TextMode="SingleLine"
runat="server" />
<p>

<asp:Button id="Button1"
Text="Validate"
OnClick="ValidateBtn_OnClick"
runat="server"/>
</form>
</body>
</html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top