Improved Input Validation - Custom Craft
(Page 5 of 9 )
So far, I have demonstrated four types of validation controls over two tutorials. This next one is the last in the entire series - and probably also the most interesting one of the lot. If you read the introduction, you'll remember the CustomValidator validation control that allows you to create customized validation routines.
Take a look at the next example that explains client-side validation using a CustomValidator validation control.
<%@ Page Language="C#" %>
<html>
<head>
<title>Odd or Even...</title>
<script language="JavaScript">
function validateNumber(oSrc, args) {
args.IsValid = (args.Value % 2 == 0);
}
</script>
<basefont face="Arial">
</head>
<body>
<asp:label id="output" runat="server" text="" />
<form runat="server" method="POST" >
<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" />
<asp:CustomValidator id="txtMyNumberCV" runat="server" ClientValidationFunction="validateNumber"
ControlToValidate="txtMyNumber" ErrorMessage="Please enter an even number." display="dynamic" /> <br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
Enter a number and tab to the Submit button. The script will immediately warn the user if he/she enters an odd number.
The first step is to add the CustomValidator control to the ASP.NET code and associate it with the server control to be validated.
<%
// 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" />
<asp:CustomValidator id="txtMyNumberCV" runat="server" ClientValidationFunction="validateNumber"
ControlToValidate="txtMyNumber" ErrorMessage="Please enter an even number." display="dynamic" /> <br/>
// snip
%>
As you can see above, many of the attributes of this new CustomValidator control are similar to the ones encountered before. However, there is one new attribute, the "ClientValidationFunction" attribute, which is unique to this control. More on this in a moment.
Next: validateNumber() function >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire