Improved Input Validation - A Closer Look
(Page 7 of 9 )
Here is a closer look at the code for this example:
<%
// snip
<asp:label id="lblMyNumber" runat="server" text="Please enter your favourite even number: " /><asp:textbox id="txtMyNumber" runat="server" />
<asp:RequiredFieldValidator id="txtMyNumberRFV" ControlToValidate="txtMyNumber" ErrorMessage="Please enter a number" runat="server" display="dynamic" EnableClientScript="false"/>
<asp:CustomValidator id="txtMyNumberCV" runat="server" OnServerValidate="NumberValidate" ControlToValidate="txtMyNumber" ErrorMessage="Please enter an even number." display="dynamic" EnableClientScript="false" /> <br/>
// snip
%>
The only difference between the two examples is that I have used the "OnServerValidate" attribute here instead of the "ClientValidationFunction" attribute used in the previous example. From the nomenclature of the attribute, it is clear that this attribute is used to associate a function with the validation control, in this case the NumberValidate() function.
<%
protected void NumberValidate(object source, ServerValidateEventArgs
args) {
args.IsValid = (Convert.ToInt16(args.Value)%2 == 0);
}
%>
Once again, you can write your own custom code so long as the function follows the following syntax:
protected void MyValidationFunction
(object source, ServerValidateEventArgs
args) {
// code comes here
}
Instead of using the vanilla HTML <submit> form control, I have opted for an ASP.NET server control, as shown below.
<%
<asp:Button OnClick="Submit_Click" Text="Submit" runat="server" />
%>
This <asp:button> control comes with a handy "OnClick" attribute that can be used to assign a function. In the example above, I have defined a Submit_Click() function for this purpose.
<%
void Submit_Click(object source, EventArgs args) {
if (IsValid) {
output.Text = "Thank you very much.";
} else {
output.Text = "Sorry, an error has occurred.";
}
}
%>
Basically, this function checks the status of the "IsValid" property of the ASP.NET page. I had told you earlier that this property is set to "true" if there are no validation errors or "false" if any of the server control validation rules fail. The Submit_Click() function then utilizes this property to update the text in the label server control with an appropriate message.
Next: A Comedy of Errors >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire