Asp.NET Controls Validation using jQuery 1.10.2 - c#

I want to validate asp.net controls using jQuery. I want to show validation in Asp.NET Label if TextBox is empty and after all validation, if it satisfies condition then allow Button to fire its backend Code.
I am using jQuery 1.10.2.min in my whole Project which after Body Part in Master Page. So do I need to put in Head Part ???
My Code :
<asp:TextBox ID="txtFirstName" runat="server" ></asp:TextBox>
<asp:Label ID="lblNote" runat="server" ></asp:Label>
<asp:Button ID="btnRegister" runat="server" Text="Create an account" OnClick="btnRegister_Click" />
Head :
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form1").validate({
rules: {
<%=txtFirstName.UniqueID %>:{
required:true
},
<%=txtEmail.UniqueID %>: {
required: true,
email: true
}
}, messages: {
<%=txtFirstName.UniqueID %>:{
required: "* Required Field *"
}
}
});
});
</script>
It is showing me error : TypeError: $(...).validate is not a function

Why don't you use asp.net built in RequiredFieldValidator.
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtFirstName" ErrorMessage="Required field"></asp:RequiredFieldValidator>
<asp:Button ID="btnRegister" runat="server" Text="Create an account" OnClick="btnRegister_Click" />

Related

ASP.NET ValidationGroup not working server-side

I have a page with two sets of controls, with ValidationGroup set differently for each set, but if I attempt to fill in one form correctly, the validators for the other form stop the Click event from firing.
I've noticed that it's behaving normally client-side, but the button then causes a postback event and the server validators do not seem to be honouring the validation groups. I'm unsure what I'm doing wrong. Surely the built in validators all support validation groups on the server side?
Below is a complete standalone example:
<%# Page Language="C#" %>
<script runat="server">
protected void SubmitButton_Click(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid) label.Text = "OK: " + ((Button)sender).ID.ToString();
}
</script>
<!DOCTYPE html>
<html>
<head runat="server">
<style>
body { font-family: sans-serif;}
.warning { color: red;}
</style>
</head>
<body>
<form id="f1" runat="server">
<h1>Validator Test</h1>
<asp:Label ID="label" runat="server" Font-Bold="true" ForeColor="Green" EnableViewState="false" /><br />
<div style="width:40%; float:left; height:200px; border:1px solid #eee; padding:15px; margin:5px;">
<h2>Left Form:</h2>
Email: <asp:TextBox ID="leftBox" runat="server" Columns="20" MaxLength="80" Width="160px" ValidationGroup="LEFT" />
<asp:RequiredFieldValidator ID="left2" runat="server" ControlToValidate="leftBox"
ErrorMessage="You must enter a value." ValidationGroup="LEFT">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rev8" runat="server" ControlToValidate="leftBox" ValidationGroup="LEFT" Text="*"
ErrorMessage="Email address format is invalid." ValidationExpression="^[\.\-\w]+#([\w\-]+\.)+\w+$" />
<asp:Button ID="LeftSubmitButton" runat="server" Text="Save Left" OnClick="SubmitButton_Click" ValidationGroup="LEFT" />
<asp:ValidationSummary ID="LeftValidationSummary" runat="server" HeaderText="Error:" ValidationGroup="LEFT" CssClass="warning" />
</div>
<div style="width:40%; float:left; height:200px; border:1px solid #eee; padding:15px; margin:5px;">
<h2>Right Form:</h2>
Email: <asp:TextBox ID="rightBox" runat="server" Columns="20" MaxLength="80" Width="160px" ValidationGroup="RIGHT" />
<asp:RequiredFieldValidator ID="rfv9" runat="server" ControlToValidate="rightBox"
ErrorMessage="You must enter an value." ValidationGroup="RIGHT">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rev10" runat="server" ControlToValidate="rightBox" ValidationGroup="RIGHT" Text="*"
ErrorMessage="Email address format is invalid." ValidationExpression="^[\.\-\w]+#([\w\-]+\.)+\w+$" />
<asp:Button ID="RightSubmitButton" runat="server" Text="Save Right" OnClick="SubmitButton_Click" ValidationGroup="RIGHT" />
<asp:ValidationSummary ID="RightValidationSummary" runat="server" HeaderText="Error:" ValidationGroup="RIGHT" CssClass="warning" />
</div>
</form>
</body>
</html>
Remove the explicit full page validation - that is this line:
Page.Validate(); it disregards the validation groups.
You'll notice that Page.Validate() has also override that allows you to specify the exact validation group - like Page.Validate("RIGHT"). This is intended for framework purposes; web form infrastructure already calls the proper Validate() for you so no need to call it explicitly.

Required field validator not working when OnClientClick is added in the button

hi i have a RequiredFieldValidator Like this
<asp:TextBox ID="txtEmployeeID" runat="server" MaxLength="255" CssClass="txt"
OnTextChanged="txtEmployeeID_TextChanged" AutoPostBack="True"
ValidationGroup="Save" ></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEmployeeID" runat="server"
ErrorMessage="Employee ID is required information."
ControlToValidate="txtEmployeeID" Display="None" ValidationGroup="Save"
SetFocusOnError="True"></asp:RequiredFieldValidator>
and a button like this
<asp:Button ID="btnBlockUser" runat="server" Text="Block User"
CssClass="submitBtn " OnClick="btnBlockUser_Click"
OnClientClick="javascript:return confirm('Are you sure want to Block this user ?')"
ValidationGroup="Save" />
Now the problem is that if i remove the OnClientClick in the button the RequriedFieldValidator works fine if i put it back there page posts back without showing any error message can some one explain why this is happenening??
try to use this code it will help you
<asp:RequiredFieldValidator ID="rfvEmployeeID" runat="server" ErrorMessage="Employee ID is required information."
ControlToValidate="txtEmployeeID" ValidationGroup="Save" SetFocusOnError="True"></asp:RequiredFieldValidator>
<br />
<asp:Button ID="btnBlockUser" runat="server" Text="Block User" CssClass="submitBtn" CausesValidation="true" OnClientClick="return validate();"
OnClick="btnBlockUser_Click" ValidationGroup="Save" />
<script type="text/javascript" language="javascript" >
function validate() {
if (Page_ClientValidate())
return confirm('Are you sure want to Block this user ?');
}
</script>

Tracking Textbox Entries with Google Analytics

I am trying to capture in google analytics the data that is entered into a textbox. The code that I have so far is below, I am trying to capture the data by Javascript, but I can't seem to get it to work. The CMS Platform I am using is sitecore.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="SalesRepSearch.ascx.cs" Inherits="USEndoscopy.Website.layouts.USEndoscopy.Sublayouts.SalesRepSearch" %>
<%# Import Namespace="USEndoscopy.Library.Search" %>
<script type="text/javascript">
var textbox = document.getElementById('txtZipCode'),
submitButton = document.getElementById('btnSalesRepSearch');
submitButton.onClick = function () {
_trackEvent('data-store', textbox.name, textbox.value, 0);
// 'data-store' can be replaced with whatever category of data you want, for sortability's sake
// the 0 can be replaced with any other numerical data you want - but it must be numerical
}
</script>
<p></p>
<p>
<asp:Panel DefaultButton="btnSalesRepSearch" runat="server">
<asp:TextBox ID="txtZipCode" runat="server" Width="300px"></asp:TextBox>
<asp:Button ID="btnSalesRepSearch" runat="server" CssClass="buttonregular" Text="Search" OnClick="btnSalesRepSearch_Click" />
<asp:RequiredFieldValidator ID="reqTxtZipCode" runat="server" ValidationGroup="ZipCode" ControlToValidate="txtZipCode" Display="Dynamic" ErrorMessage="Please enter a valid US Zip code" CssClass="error"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regExTxtZipCode" runat="server" ValidationExpression="^\d {5}(-\d{4})?$" ValidationGroup="ZipCode" ControlToValidate="txtZipCode" Display="Dynamic" ErrorMessage="Please enter a valid US Zip code" CssClass="error"></asp:RegularExpressionValidator>
</asp:Panel>
</p>
<p>
<asp:Repeater ID="salesRepContainer" runat="server">
<ItemTemplate>
<%# ((SalesRep)Container.DataItem).RepName %><br />
<%# ((SalesRep)Container.DataItem).Phone %><br />
<%# ((SalesRep) Container.DataItem).Email %><br />
</ItemTemplate>
</asp:Repeater>
</p>
<p>
<sc:Text Field="InternationalMessage" runat="server" />
</p>
Did you check the source code of the rendered HTML? Has the ASP.Net WebControl ID's ended up as something completely different due being nested in the panel?
Maybe you should add a CSS class to these and use document.getElementsByClassName
If you are using jQuery then you could use the attributeEndsWith selector
$('input[id$="txtZipCode"]');
$('input[id$="btnSalesRepSearch"]')
It's because ASP.NET has changed the ID value of your textboxes at the time of rendering them.
If your running .net V4 or greater then add ClientIDMode="Static" to your textbox and
button. This tells .net to not change the ID of your control.
<asp:TextBox ID="txtZipCode" runat="server" ClientIDMode="Static" Width="300px"></asp:TextBox>
<asp:Button ID="btnSalesRepSearch" runat="server" ClientIDMode="Static" CssClass="buttonregular" Text="Search" OnClick="btnSalesRepSearch_Click" />
If your running less than .net 4 change your Javascript to: (.ClientID gets the ID that .net gave the control when it rendered it)
var textbox = document.getElementById('<%= txtZipCode.ClientID %>'),
submitButton = document.getElementById('<%= btnSalesRepSearch.ClientID %>');
UPDATE
You might be having an issue where your javascript function is trying to assign a click function to your button before your button is actually available on the DOM.
So try the following:
Javascript function
function btnSearchClick(){
var textbox = document.getElementById('txtZipCode');
// Change your google code to this:
_gaq.push(['_trackEvent', textbox.name, textbox.value, 0]);
return true;
}
And on your button add the property
onClientClick="return btnSearchClick()"

Custom Validator not working but allows post back instead

<div>
<asp:Label ID="lblClientId" runat="server" CssClass="label" meta:resourcekey="lblClientIdResource" />
<asp:TextBox ID="tbClientId" runat="server" style="width:150px; "/>
<asp:Button ID="btnClientId" runat="server" style="width:50px;" meta:resourcekey="btnClientIdResource" />
<asp:CustomValidator ID="rfvClientId" runat="server" ValidationGroup="ClientId" meta:resourcekey="rfvClientIdResource" ControlToValidate="tbClientId" ClientValidationFunction="BtnClickClientId" style="position:absolute;" ValidateEmptyText="True" ><asp:Image ID="Image2" ImageUrl="caution_20.png" runat="server" /></asp:CustomValidator>
</div>
<script type="text/javascript">
function BtnClickClientId(session, args) {
ButtonClick(session, args, "<%= tbClientId.ClientID %>", "<%= lblClientId.ClientID %>");
}
window.onload = function () {
document.getElementById('<%= tbClientId.ClientID%>').focus();
};
</script>
<asp:ValidationSummary ID="ClientIdValidationSummary" runat="server" BackColor="LightGray" DisplayMode="BulletList" CssClass="validationSummary" EnableClientScript="true" HeaderText='<%$ Resources:GlobalResource, ValidationSummaryResource %>'/>
So this ButtonClick() method is working and has been tested independently. The problem is that when i enter nothing into the text box and click the button, the validator works as expected and appears on the screen. Then it disappears. It is also never shown in the page validation summary. How do I get this to work?
I have tried to also set a required field validator on this text box and it seems to work with that but I do not want to use two validators.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="tbClientId" ErrorMessage="RequiredFieldValidator" style="position:absolute;"><asp:Image ID="Image2" ImageUrl="caution_20.png" runat="server" /></asp:RequiredFieldValidator>
<asp:CustomValidator ID="rfvClientId" runat="server" ValidationGroup="ClientId" meta:resourcekey="rfvClientIdResource" ControlToValidate="tbClientId" ClientValidationFunction="BtnClickClientId" style="position:absolute;" ValidateEmptyText="True" ></asp:CustomValidator>
This code works but I should not have to use 2 validators.
You need to set the "arg.IsValid" to "true" or "false" in the javascript function based on your requirement (i.e. to "true" when you think the validation is successful and false otherwise). Also, in the code behind file, it is always advisable to check for "Page.IsValid" property inside the click event handler of the button. So, in the javascript add this.
arg.IsValid = false;
and in code behind
protected void button_click(..)
{
if (Page.IsValid)
{
// Your code, if any exists
}
}
Hope this helps!!

ASP.NET Form Fields Not POSTing from colorbox

I've got a form that is displayed inside a jQuery colorbox. When the form is submitted, the fields within that form are not being posted back to the page. I modified the javascript to store the form fields into hidden fields on a submit and those DO post back. The problem is, since this is a login box, I really don't want to move the password around like that. The main form content is inside an update panel. Here is the code for my master page:
<form id="myform" runat="server" clientidmode="Static" method="post">
<asp:ScriptManager ID="ecommerceManager" runat="server" ClientIDMode="Static" EnableViewState="False" EnablePageMethods="True">
<Scripts>
<asp:ScriptReference Path="~/js/jquery-1.6.1.min.js" />
<asp:ScriptReference Path="~/js/jquery.colorbox.min.js" />
<asp:ScriptReference Path="~/js/eCommerce.js" />
</Scripts>
</asp:ScriptManager>
<div style="width: 940px; margin-left: auto; margin-right: auto;">
<div align="left">
TOP OF THE PAGE
<asp:ContentPlaceHolder ID="bodyContent" runat="server" ClientIDMode="Static">
</asp:ContentPlaceHolder>
BOTTOM OF THE PAGE
</div>
</div>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(loadData);
</script>
</form>
Here is some of the code from my main default page that uses the master page:
<asp:Content ID="mainContent" ContentPlaceHolderID="bodyContent" runat="server">
<asp:UpdatePanel ID="ecommerceUpdate" runat="server" ClientIDMode="Static">
<ContentTemplate>
<asp:Panel ID="pnlEcomMain" runat="server" CssClass="ecom_main" ClientIDMode="Static">
<asp:HiddenField ID="statusField" runat="server" ClientIDMode="Static" ViewStateMode="Disabled" EnableViewState="False" />
<asp:HiddenField ID="hdnUsername" runat="server" ClientIDMode="Static" ViewStateMode="Disabled" EnableViewState="False" />
<div class="add_product">
<div class="add_product_menu text_12_bold">
<asp:Image ID="imgAddProducts" ImageUrl="~/images/ecom_icon_add_2.gif" CssClass="std_btn" AlternateText="Add Products" runat="server" ClientIDMode="Static" />Add Additional Products:<br /><br />
<asp:DropDownList ID="newproduct" runat="server" ClientIDMode="Static"
onchange="addProduct()">
</asp:DropDownList>
</div>
</div>
</asp:Panel>
<div class="clear"></div>
<!--- HERE IS THE COLORBOX POPUP CONTENT --->
<div style="display: none; visibility: hidden;">
<div id="inline_login">
<p><strong>User Login Details Go Here</strong></p>
User Name: <asp:TextBox ID="loginName" runat="server" ClientIDMode="Static" EnableViewState="False" ViewStateMode="Disabled" /><br />
Password: <asp:TextBox ID="loginPassword" runat="server" TextMode="Password" ClientIDMode="Static" /><br />
<input type="button" name="loginBtn" id="loginbtn" value="Login" onclick="javascript:validateLogin()" />
</div>
</div>
</asp:Panel>
<asp:Label ID="xmlContent" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
The new product field properly posts, but the username and password doesn't UNLESS I copy it to the hidden fields before a post. I'm guessing maybe it's a conflict with the update panel? I was originally trying to get a Login Control working in the Update Panel but read in the forums that there is a known problem with this.
Any insight on this would very tremendously be appreciated. I'm using firebug and can confirm that the fields simply aren't in the post which is why ASP isn't finding them.
Apparently, despite being inside the form, the colorbox actually moves the content outside the form. I was able to resolve this by adding this line of code to my JavaScript submit function:
jQuery('#inline_login').appendTo('form');
Hope it helps someone else!
I have never used jQuery colorbox, but i had a similar problem with jQuery UI modal popup. What it was doing was, when i attached the popup it moved the content div outside of the asp.net form so the controls were not getting posted back.
Another option that worked for me in a particular .NET CMS (DNN) was to take Jack's fix and attach to the cbox_complete event. Posting in case someone else might find this useful.
$(document).bind('cbox_complete', function () {
$("#colorbox, #cboxOverlay").appendTo('form:first');
});
Just had a similar problem with colorbox & form, solved it this way. My problem was that the submit wasn't working since the fieldsets were stripped of the form tag; So if your form isn't posting in colorbox, try this, sending in the form id as the href for the colorbox content
$(document).ready(function () {
$('#login-trigger').click(function () {
$.colorbox({
inline: true,
href: "#login-form",
close: "×",
onOpen: function () { $('#login-content').css({ display: 'block' }); },
onClosed: function () { $('#login-content').css({ display: 'none' }); }
});
return false;
});

Categories