I’m writing a user control that uses jquery.validate instead of the validation controls to work with required/email fields. I build a quick test page and everything worked fine. However if I extracted some of the functionality into a web control and dropped that onto the page, then the if(Page.IsValid) { } check in the code-behind always seems to be true and none of the validation seems to work anymore. Here is the code I’m using for the web control:
Front-end:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" I nherits="JqueryValidateTest.TestControl" %>
<div id="control-wrapper">
<asp:TextBox ID="txtName" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:TextBox ID="txtEmail" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
</div>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
Response.Write("Page is valid");
else
Response.Write("Page is not valid");
}
This is the html/js for the page the control is dropped onto:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JqueryValidateTest.Default" %>
<%@ Register Src="TestControl.ascx" TagName="TestControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
input.valid
{
border: 2px solid lime;
}
input.error
{
border: 2px solid red;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"> </script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function () {
jQuery.validator.messages.required = "";
jQuery.validator.messages.email = "";
$('#form1').validate({
rules:
{
txtName: {
required: true
},
txtEmail: {
required: true,
email: true
}
},
messages: {}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:TestControl ID="TestControl1" runat="server" />
</div>
</form>
</body>
</html>
I thought it may be something to do with the ids of the controls changing but I’ve changed the ClientIDMode to static and they seem to be staying the same.
Does anyone know why this is failing?
Thanks
Use this :