How to Hide error message of a asp custom validator - c#

I am using asp requiredfieldvalidator. I want the required field validator to fire only when a checkbox on my form is checked.
When the checkbox is fired, the validator works as expected and error message shows up but when the checkbox is unchecked the errormessage that showed up stays on the screen. I have tried different options like validator.resetForm(); disabling the validator, hiding the validator but the error message stays on the screen form. Here is the simplified version of my code:
<script src="jquery-1.4.2.min.js"></script>
<!DOCTYPE html>
<script type="text/javascript">
function enableDisableControls(value) {
var enabledSilentPost = $("#<%=chkEnableSilentPost.ClientID%>").attr("checked");
var validatorControl = $("#<%=valApprovalURL.ClientID%>")[0];
ValidatorEnable(validatorControl, enabledSilentPost);
// If the checkbox is false then assume that the
if (!enabledSilentPost) {
validatorControl.enabled = false;
}
}
$(document).ready(function () {
$("#<%=chkEnableSilentPost.ClientID%>").click(function () {
enableDisableControls();
});
enableDisableControls();
});
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:CheckBox ID="chkEnableSilentPost" runat="server" Width="250px" Text="Enable" />
<asp:Label ID="lblApprovalURL" runat="server" Text="URL" CssClass="controllabel" meta:resourcekey="lblApprovalURLResource"></asp:Label>
<asp:TextBox ID="txtApprovalURL" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="valApprovalURL" runat="server" ControlToValidate="txtApprovalURL" ErrorMessage="Please enter Valid Text" Text="*"></asp:RequiredFieldValidator>
<actk:ValidatorCalloutExtender ID="extApprovalURL" TargetControlID="valApprovalURL" runat="server" Enabled="True"></actk:ValidatorCalloutExtender>
</div>
</form>

I am was able to get the validators to react by doing the following. The Validator was pretty simpe, but I had to predict the ID of the Extender in order for it to work:
<script type="text/javascript">
$(function () {
$('#<%=chkEnableSilentPost.ClientID %>').click(function () {
$("#<%=valApprovalURL.ClientID %>").toggle(this.checked);
$("#extApprovalURL_popupTable").toggle(this.checked);
});
});
</script>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" />
<div>
<asp:CheckBox ID="chkEnableSilentPost" runat="server" Width="250px" Text="Enable" />
<asp:Label ID="lblApprovalURL" runat="server" Text="URL" CssClass="controllabel" meta:resourcekey="lblApprovalURLResource"></asp:Label>
<asp:TextBox ID="txtApprovalURL" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="valApprovalURL" runat="server" ControlToValidate="txtApprovalURL" ErrorMessage="Please enter Valid Text" Text="*"></asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="extApprovalURL" TargetControlID="valApprovalURL" runat="server" Enabled="True"></asp:ValidatorCalloutExtender>
</div>
</form>

Related

How to verify on valid

How can I show a green checkbox image beside textbox on valid usage ?
I'm trying to show this when the user passed to next textbox.
Here is my code for invalid usage
<asp:TextBox ID="TextBoxEMail" runat="server" ValidationGroup="Valid1"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" ErrorMessage="EMail is invalid"
ControlToValidate="TextBoxEMail"
ValidationGroup="Valid1" Display="Dynamic" ForeColor="Red"
ValidationExpression="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*
[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"></asp:RegularExpressionValidator>
You can do it by using JavaScript (or jQuery).
Here is an example of javascript.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="WebApplication1.Test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link type="text/css" rel="stylesheet" href="Content/Site.css" />
<title></title>
<script type="text/javascript">
function checkMailAddress(tb) {
var regEx = RegExp(/^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
var img = document.getElementById("imgValidate");
if (regEx.test(tb.value)) {
img.style.display = "block";
}
else
img.style.display = "none";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtEmail" runat="server" onchange="checkMailAddress(this)"></asp:TextBox>
<asp:Image ID="imgValidate" runat="server" Height="18px" ImageUrl="~/Images/Ok.png" Width="22px" CssClass="validationImage" />
</div>
</form>
</body>
</html>
And in the site.css :
.validationImage
{
display:none;
}
The site.css is in the Content folder in the project. And the image Ok.png is in the Images folder.

checkbox autopostback without refreshing page asp net

I have this checkbox that I need to be AutoPostBack="True" so that I can trigger OnCheckedChanged="chkCompany_OnCheckedChanged". The problem is that I dont want the page to be refreshed and redirected, I want the user to stay put exactly where they are.
ASPX:
<asp:CheckBox OnCheckedChanged="chkCompany_OnCheckedChanged" AutoPostBack="True" CssClass="chkCompany" ClientIDMode="Static" ID="chkCompany" runat="server" />
C#:
protected void chkCompany_OnCheckedChanged(object sender, EventArgs e)
{
if (chkCompany.Checked)
{
txtName.Visible = false;
}
else
{
txtName.Visible = true;
}
}
You should use UpdatePanel control to do this
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:CheckBox OnCheckedChanged="chkCompany_OnCheckedChanged" AutoPostBack="True" CssClass="chkCompany" ClientIDMode="Static" ID="chkCompany" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
Keep your code inside update pannel.
you can use javascript to do this,if Update panel does not work.
<!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">
<script type=text/javascript>
function CheckedChanged()
{
if((document.getElementById('chkCompany').checked))
`{`
document.getElementById('txtname').Visible=false;
}
`else`
{
document.getElementById('txtname').Visible=false;
`}`
}
</script>
</head>
<body>
<asp:CheckBox OnCheckedChanged="CheckedChanged" AutoPostBack="false" CssClass="chkCompany" ClientIDMode="Static" ID="chkCompany" runat="server" />
<asp:TextBox ID="txtname" runat="server"/>
</body>
</html>
-----------------------------------------------------------------------------
Here is another solution but for DropDownCheckList.
The same works for CheckBox.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<cwc:DropDownCheckList runat="server" ID="myId" AutoPostBack="True" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="myId" />
</Triggers>
</asp:UpdatePanel>

ajaxToolkit:TabContainer confirm when adding tab

I want my ajaxToolkit:TabContainer to have a tabpanel that allows the user to add another tab. I only want it to postback when they have clicked the "+" tabpanel and no other.
I can't seem to stop the event bubbling in the Javascript:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript">
function checkTab(sender, e) {
if (sender.get_activeTab().get_headerText().replace("<span>", "").replace("</span>", "") != "+") {
cancelBubble(e);
}
else {
if (!confirm('Are you sure?')) {
cancelBubble(e);
}
}
}
function cancelBubble(e) {
if (e) {
e.stopPropagation();
}
else {
window.event.cancelBubble = true;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager" runat="server">
</asp:ScriptManager>
<ajaxToolkit:TabContainer ID="MyTabContainer" runat="server" OnActiveTabChanged="MyTabContainer_OnActiveTabChanged"
AutoPostBack="true" OnClientActiveTabChanged="checkTab">
<ajaxToolkit:TabPanel ID="TabPanel1" runat="server" HeaderText="My First Tab" Enabled="true">
<ContentTemplate>
My first tab
</ContentTemplate>
</ajaxToolkit:TabPanel>
<ajaxToolkit:TabPanel ID="AddTabPanel" runat="server" HeaderText="+" Enabled="true">
<ContentTemplate>
</ContentTemplate>
</ajaxToolkit:TabPanel>
</ajaxToolkit:TabContainer>
</div>
</form>
</body>
</html>
protected void MyTabContainer_OnActiveTabChanged(object sender, EventArgs e)
{
TabPanel tp = new TabPanel();
tp.HeaderText = "New Tab";
MyTabContainer.Tabs.Add(tp);
}
Thanks,
Alex
You can use return false; in JavaScript to stop a PostBack. So I think all you need is this:
function checkTab(sender, e)
{
if (sender.get_activeTab().get_headerText().replace("<span>", "").replace("</span>", "") != "+")
{
return false;
}
else
{
return confirm('Are you sure?');
}
}
Add script below to your project and add reference on at at very bottom of page:
Sys.Extended.UI.TabPanel.prototype.raiseClick = function (eventArgs) {
var eh = this.get_events().getHandler("click");
if (eh) {
eh(this, eventArgs);
}
};
Sys.Extended.UI.TabPanel.prototype._header_onclick = function (e) {
e.preventDefault();
var eventArgs = new Sys.CancelEventArgs();
this.raiseClick(eventArgs);
if (eventArgs.get_cancel() === true)
return;
this.get_owner().set_activeTab(this);
this._setFocus(this);
};
Now we add capability to cancel click on particular tab on client. The sample of usage:
<script type="text/javascript">
function AddTabOnClientClick(sender, args) {
args.set_cancel(!confirm("Are you sure?"));
}
</script>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajaxToolkit:ToolkitScriptManager>
<div>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<ajaxToolkit:TabContainer ID="MyTabContainer" runat="server" AutoPostBack="true"
ActiveTabIndex="0">
<ajaxToolkit:TabPanel ID="TabPanel1" runat="server" HeaderText="My First Tab" Enabled="true">
<ContentTemplate>
My first tab
</ContentTemplate>
</ajaxToolkit:TabPanel>
<ajaxToolkit:TabPanel ID="AddTabPanel" runat="server" HeaderText="+" OnClientClick="AddTabOnClientClick">
<ContentTemplate>
</ContentTemplate>
</ajaxToolkit:TabPanel>
</ajaxToolkit:TabContainer>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
<script src="Scripts/MyAjaxToolkitExtensions.js" type="text/javascript"></script>
Thanks to jadarnel27, this is the final solution I went for:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript">
<script type="text/javascript">
function addTab() {
if (confirm('Are you sure?')) {
document.getElementById('<%=AddTabButton.ClientID %>').click();
}
}
</script>
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager" runat="server">
</asp:ScriptManager>
<asp:Button ID = "AddTabButton" runat="server" OnClick="AddTabButton_OnClick" CssClass="DisplayNone" />
<ajaxToolkit:TabContainer ID="MyTabContainer" runat="server">
<ajaxToolkit:TabPanel ID="TabPanel1" runat="server" HeaderText="My First Tab" Enabled="true">
<ContentTemplate>
My first tab
</ContentTemplate>
</ajaxToolkit:TabPanel>
<ajaxToolkit:TabPanel ID="AddTabPanel" runat="server" HeaderText="+" Enabled="true" OnClientClick="addTab">
<ContentTemplate>
</ContentTemplate>
</ajaxToolkit:TabPanel>
</ajaxToolkit:TabContainer>
</div>
</form>
</body>
</html>
protected void AddTabButton_OnClick(object sender, EventArgs e)
{
TabPanel tp = new TabPanel();
tp.HeaderText = "New Tab";
MyTabContainer.Tabs.Add(tp);
}

Calling C# getter from UpdatePanel / javascript - never get updated data

I have this property in my code-behind.
public string LocationOptions
{
get { return Session["LocationOptions"].ToString(); }
set { Session["LocationOptions"] = value; }
}
On the front-end, I have this javascript.
<script type="text/javascript">
function pageLoad(sender, args) {
InitLocationsAutoComplete();
}
</script>
<asp:UpdatePanel ID="upScript" runat="server">
<ContentTemplate>
<script type="text/javascript">
function InitLocationsAutoComplete() {
var locationsJson = '<%= LocationOptions %>';
alert(locationsJson);
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
I'm setting a breakpoint on my getter and setter in the C# code.
I'm using MVP and the setter gets called from a presenter.
On first page load, things work as expected. The breakpoint on the setter gets hit first. Then the breakpoint on the getter. Finally, I get a javascript alert with the value I expect to see.
I'm running into problems on partial postbacks that are triggered by other update panels. On those, my setter breakpoint hits with a new value. My getter breakpoint gets hit next, and if I quick watch Session["LocationOptions"] I see the new value there. But when I get the javascript alert, it still alerts the initial value from the first page load.
If it still calls the property in C#, then I don't see why the updated value doesn't come through to the javascript. Why am I stuck with the initial value from first page load?
As far as I know, javascript in the partially updated content is not re-executed/re-evaluated. My understanding is that the partial update will essentially edit the DOM to update a part of the page, but this does not allow one to dynamically upate javascript on the page. You can use ScriptManager.RegisterClientScriptBlock on the server-side to register your updated javascript during the partial postback.
I've had the same issue in the past.
The issue is due to the fact that the dom is only partially updated, i've personally corrected this by registering the script in the ScriptManager.
An example of this is here: ScriptManager.RegisterClientScriptBlock Method (Control, Type, String, String, Boolean)
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_PreRender(object sender, EventArgs e)
{
string script = #"
function ToggleItem(id)
{
var elem = $get('div'+id);
if (elem)
{
if (elem.style.display != 'block')
{
elem.style.display = 'block';
elem.style.visibility = 'visible';
}
else
{
elem.style.display = 'none';
elem.style.visibility = 'hidden';
}
}
}
";
ScriptManager.RegisterClientScriptBlock(
this,
typeof(Page),
"ToggleScript",
script,
true);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>ScriptManager RegisterClientScriptInclude</title>
</head>
<body>
<form id="Form1" runat="server">
<div>
<br />
<asp:ScriptManager ID="ScriptManager1"
EnablePartialRendering="true"
runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1"
UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<asp:XmlDataSource ID="XmlDataSource1"
DataFile="~/App_Data/Contacts.xml"
XPath="Contacts/Contact"
runat="server"/>
<asp:DataList ID="DataList1" DataSourceID="XmlDataSource1"
BackColor="White" BorderColor="#E7E7FF" BorderStyle="None"
BorderWidth="1px" CellPadding="3" GridLines="Horizontal"
runat="server">
<ItemTemplate>
<div style="font-size:larger; font-weight:bold; cursor:pointer;"
onclick='ToggleItem(<%# Eval("ID") %>);'>
<span><%# Eval("Name") %></span>
</div>
<div id='div<%# Eval("ID") %>'
style="display: block; visibility: visible;">
<span><%# Eval("Company") %></span>
<br />
<a href='<%# Eval("URL") %>'
target="_blank"
title='<%# Eval("Name", "Link to the {0} Web site") %>'>
<%# Eval("URL") %></a>
</asp:LinkButton>
<hr />
</div>
</ItemTemplate>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<AlternatingItemStyle BackColor="#F7F7F7" />
<ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
i hope this helps.

clientvalidation in asp.net

I am trying to create a required field validation with a customvalidator. However when the field is empty it still does a postback?
<body>
<form id="Form1" runat="server">
<h3>
CustomValidator ServerValidate Example</h3>
<asp:Label ID="Message" Font-Name="Verdana" Font-Size="10pt" runat="server" />
<p>
<asp:TextBox ID="Text1" runat="server" Text="[Name:required]" />
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="Text1" ClientValidationFunction="ClientValidate"
Display="Static" ErrorMessage="" ForeColor="green" Font-Name="verdana" Font-Size="10pt"
runat="server" />
<p>
<asp:Button ID="Button1" Text="Validate" OnClick="ValidateBtn_OnClick" runat="server" />
</form>
</body>
</html>
<script language="javascript">
function ClientValidate(source, arguments) {
alert(arguments.Value.length);
if (arguments.Value != "[Name:required]" && arguments.Value.length > 0) {
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
Add ValidateEmptyText="True" to your CustomValidator tag
See here for more details.
You should move your <script> tag containing the ClientValidate function to inside your <html> tags, preferably inside the <body> or <head> tags.

Categories

Resources