I had some time to kill and I reverse engineered Google's input form to my own liking.
I want to post this because I had a hard time figuring out how to add a special error class to a control that failed validation so that it would have a red outline on it. There are tons of examples online but many of them didn't work or were extremely verbose. This example is the most elegant imo.
Client side-code
Code:
<script type="text/javascript">
//<![CDATA[
function ValidateControls(source, args) {
// validation logic here
if (args.Value == "") {
args.IsValid = false;
}
else {
args.IsValid = true;
}
// change control's color to red if failed
var ctrl = $('#' + source.controltovalidate);
if (!args.IsValid) {
if (ctrl)
ctrl.addClass("errorBox");
}
else {
if (ctrl)
ctrl.removeClass("errorBox");
}
}
//]]>
</script>
XHTML exmaple
HTML Code:
<span>First Name</span>
<asp:TextBox ID="TxtFName" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CVTxtName" runat="server" Display="Static"
ValidateEmptyText="true" ControlToValidate="TxtFName"
ClientValidationFunction="ValidateControls" CssClass="validators"
ErrorMessage="Enter your first name." onservervalidate="ValidateRequiredField">
</asp:CustomValidator>
And like Imar's book says, I also validate at the server side
Code:
protected void ValidateRequiredField(object source, ServerValidateEventArgs args)
{
// if field is empty signal validation fail
if (!string.IsNullOrEmpty(args.Value))
args.IsValid = true;
else
args.IsValid = false;
}
protected void LBSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// submit records
}
}
If anyone has any critiques on this code please feel free to comment, especially Imar. I'm sure you have an even better solution for this. ; )