Updated 09SEP08: Now working in FF3, Jörn Zaefferer pointed out via the jQuery Mailing List that my script tag declaration was incorrect. I also added a better RegEx for the phone number.
I have been working on a proof of concept for a way to insert a bunch of contact data for a record. One of the requirements that has been pretty challenging is the client side validation since a lot of info isn't known until run time.
Demo (Tested in FF3, IE7, Chrome & Opera 9.5) | Download
- User could enter anywhere from 1 to 5 contact methods in the case of this example.
- If a type is entered then info is required and vice versa.
- Depending upon the type chosen the validation is different.
So far I am using the jQuery Validation Plugin by Jörn Zaefferer which appears to have been around for quite a while with a big following.
Here is all of the jQuery:
$(document).ready(function() {
$("#myform").validate({
//change the default placement of the error label
errorPlacement: function(error, element) {
error.appendTo(element.parent("td").parent("tr").find(".errorTD"));
}
});
//Add custom phone number validator - needs to be improved
jQuery.validator.addMethod("phone", function(value, element) {
return this.optional(element) || /^\d{3}-\d{3}-\d{4}$/.test(value);
}
, "* Please enter a phone number formated like XXX-XXX-XXXX");
$(".wrapper").each(function() {
var ddl = $(this).find(".type");
var txt = $(this).find(".info");
//Setup validation for dropdowns
txt.blur(function() {
//remove any existing rules
ddl.rules("remove");
var tst = txt.val();
if (tst !== "") {
ddl.attr("title", "* Selection of a type is required.");
ddl.rules("add", {
required: true
});
}
else {
ddl.attr("title", "");
}
});
//Setup validation for text boxes
ddl.blur(function() {
//remove and existing rules
txt.rules("remove");
var tst = ddl.val();
if (tst != "") {
txt.rules("add", {
required: function(element) {
return ddl.val() != "";
}
});
//If it is email add validation for email
if (ddl.val() == "3") {
txt.attr("title", "* Please enter a valid email address.")
txt.rules("add", {
email: true
});
}
else { //Has to be a phone number then
txt.attr("title", "* Please enter a phone number in XXX-XXX-XXXX format.")
txt.rules("add", {
phone: true
});
}
}
});
});
});
And the HTML for the first Row:
<tr class="wrapper">
<td>1.</td>
<td>
<asp:DropDownList ID="DropDownListType1" runat="server" CssClass="type">
<asp:ListItem Text="" Value=""></asp:ListItem>
<asp:ListItem Text="Office Phone" Value="1"></asp:ListItem>
<asp:ListItem Text="Mobile Phone" Value="2"></asp:ListItem>
<asp:ListItem Text="Email" Value="3"></asp:ListItem>
<asp:ListItem Text="Fax" Value="4"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:TextBox ID="TextBoxInfo1" runat="server" CssClass="info"></asp:TextBox>
</td>
<td class="errorTD">
</td>
</tr>
So I think I have a good start, but it could be improved still. Let me know what you think and what I missed.