Unable to enable/disable validator in control embedded in UpdatePanel - asp.net

Arg. Inheriting projects is SO much fun. Especially when they don't work well, and even more especially when they contain UpdatePanels...
I have a shipping address user control inside an UpdatePanel. We need to be able to process international addresses, so one thing I've done is show/hide the State dropdown depending on if the country selected is US or not. In addition, I have a RequiredFieldValidator on that dropdown.
When the user control is used on a normal page elsewhere in the application, everything is great. However, in the UpdatePanel, .NET is not seeing the RFV even though JavaScript does.
Address.ascx: (snipped)
<li class="form-list-question question-state">
<span class="form-label">
<asp:Label ID="lblState" runat="server" SkinID="FieldLabel" AssociatedControlID="ddlState" Text="State" /></span>
<asp:DropDownList ID="ddlState" runat="server" SkinID="State" DataSourceID="dsStates" AppendDataBoundItems="true" ViewStateMode="Enabled"
DataTextField="Name" DataValueField="Abbr" CssClass="required">
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvState" runat="server" EnableClientScript="true" Display="None" ControlToValidate="ddlState"
ErrorMessage="State is required." ValidationGroup="Address" />
</li>
address.js: (snipped)
function SetFormByCountry() {
if (isUsTerritory()) {
$('.question-state').show();
if ($('#rfvState').length > 0) {
$('#rfvState').enabled = true;
}
} else {
$('.question-state').hide();
if ($('#rfvState').length > 0) {
$('#rfvState').enabled = false;
}
}
}
Current behavior: When a country other than the US is selected, the State dropdown disappears as appropriate, but when the form is submitted, validation still occurs on the now hidden dropdown. There are no JS errors created.
Expected behavior: Given the above scenario, the RequiredFieldValidator should be disabled and the form should post.

Have you tried using the ValidatorEnable function?
It's an ASP.Net javascript function that can be used to turn off client side validators; in your example, you should be able to do the following in your client side javascript (where you set the enabled property):
ValidatorEnable(document.getElementById('<%=rfvState.ClientID%>'), false);
My only other suggestion is to fire a async postback when the country is changed and remove the state validator server side.

Related

How to use a custom ValidatorUpdateDisplay function when the controls / validators are loaded on postback in an UpdatePanel the first time?

In ASP.NET when using validation controls (i.e. RequiredFieldValidator) the client sided framework will execute the JS function Page_ClientValidate. This function will validate all controls on the page (of the given ValidationGroup) and call the JS function ValidatorUpdateDisplay with a parameter of the DOM element of the span tag of the validator control.
ValidatorUpdateDisplay toggles the visibility of the span tag depending on the result of the validation.
In my web application I've overridden the ValidatorUpdateDisplay JS function to provide more functionality on the validation scenario (i.e. red borders around the controls, showing popover on the first failed control and scrolling to it).
Now this works very well until my controls (incl. submit button) are shown the first time after a postback in an UpdatePanel.
<asp:ScriptManager runat="server" />
<asp:UpdatePanel ID="upTest" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="bShow" runat="server" UseSubmitBehavior="false" Text="SHOW" OnClick="bShow_Click" />
<asp:Panel ID="pContent" runat="server" Visible="false">
<asp:TextBox ID="tbTest" runat="server" />
<asp:RequiredFieldValidator ID="rfvTest" runat="server" ControlToValidate="tbTest" Text="Not valid" />
<asp:Button ID="bTest" runat="server" UseSubmitBehavior="false" Text="TEST" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function ValidatorUpdateDisplay(val) {
debugger; // this will not be reached
}
</script>
protected void bShow_Click(object sender, EventArgs e)
{
this.pContent.Visible = true;
}
After initial load press bShow to display pContent.
Now, if you leave tbTest.Text empty and press on bTest it should enter the overridden ValidatorUpdateDisplay function, however it enters the function of the framework and displays "Not valid" from rfvTest.
If you change pContent.Visible to true and press bTest after initial load the desired effect will happen: It will enter the custom ValidatorUpdateDisplay function and not display "Not valid".
If you move the button bTest out of the UpdatePanel the problem persists.
How can I make it work inside an UpdatePanel?
ASP.NET uses a lazy loading approach to insert the ValidatorUpdateDisplay function when it needs it the first time, hence in my example it will load the function after the postback of the UpdatePanel.
This will override my own implementation of the ValidatorUpdateDisplay function, because it's inserting the function at the end of the page.
There is a dirty workaround, I just inserted an empty CustomValidator on initial load that is always valid:
<asp:CustomValidator runat="server" />
I wish there was a cleaner solution.

Multiple validation groups, only validate one on control blur

Summary
I have a single control with two (almost) identical validators, each linked to two validation groups. When the cursor leaves the control, both validators are automatically checked by ASP.NET. Is there a way to only fire one (without setting EnableClientScript="false") so there are not two * symbols being displayed on the blur?
Details
I have a form with two buttons asp:btnSave and asp:btnSubmit... both buttons require validation, as certain controls must be validated on the save for it to work correctly.
So I have two validation groups, the "default" group for submitting (i.e. ValidationGroup property is NOT set), and the "SaveGroup" for saving. There are two asp:ValidationSummary controls to reflect these.
On a single control that is (for example) designed to accept a decimal value, I have the following. Firstly a required field for the submit, then a range validator for the submit. Then a 3rd validator which is a replication of the range validator but is part of the "SaveGroup"...
<asp:TextBox runat="server" id="txtMyDecVal" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtMyDecVal"
Text="*" ErrorMessage="Enter a value" />
<asp:RangeValidator runat="server" ControlToValidate="txtMyDecVal" Type="Double"
MinimumValue="0" MaximumValue="999.99" Text="*"
ErrorMessage="Value must be between 0 and 999.99" />
<asp:RangeValidator runat="server" ControlToValidate="txtMyDecVal" Type="Double"
MinimumValue="0" MaximumValue="999.99" Text="*"
ErrorMessage="Value must be between 0 and 999.99"
ValidationGroup="SaveGroup" />
This is working fine, and the two buttons validate correctly.
The problem is... there is a visual issue that if you type invalid text into the control, BOTH the RangeValidators are fired automatically by ASP.NET when the cursor leaves the control, resulting in two * symbols appearing.
Is there a way to make it so that only one of those validators are checked as part of the blur event on the control?
I could set EnableClientScript="false" on one of the validators, but I still want it to check the control on the client side without a post-back first.
Update
I have been playing with setting EnableClientScript="false" as I decided that the post-back on the save wasn't actually going to be a big issue.
However, this then leads on to another visual issue: Enter invalid text, the "submit" validator shows the *. Click the save, which posts-back and then displays the * for the "save" validator. If you then change the text to valid text, the "save" validator doesn't disappear, so it still looks like there's a problem... and if you change the text to different invalid text, you get the "submit" * appearing as well, resulting in the same as before... i.e. two * symbols.
You should add Display="Dynamic" to your validators.
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtMyDecVal"
Text="*" ErrorMessage="Enter a value" Display="Dynamic" />
<asp:RangeValidator runat="server" ControlToValidate="txtMyDecVal" Type="Double"
MinimumValue="0" MaximumValue="999.99" Text="*"
ErrorMessage="Value must be between 0 and 999.99" Display="Dynamic" />
<asp:RangeValidator runat="server" ControlToValidate="txtMyDecVal" Type="Double"
MinimumValue="0" MaximumValue="999.99" Text="*"
ErrorMessage="Value must be between 0 and 999.99"
ValidationGroup="SaveGroup" Display="Dynamic"/>
Courtesy of Satheesh babu's artice, and having toyed with a couple of options -- I think the best way to deal with complex situations is to DIY.
I've set CausesValidation="False" and removed ValidationGroups from buttons, and put something like:
OnClientClick="if (EnableVal(['ValidationGroup1','ValidationGroup2']) == false) {return false;}"
for client-side validations, where particular buttons validate increasingly complex rules as the process moves ahead. This allows me to reduce duplicating validators.
Then, on server-side, I am calling Page.Validate("ValidationGroup#") for each group, depending on the buttons or even business process state, and then finally checking Page.IsValid.
Also, depending on the business process state, the buttons' OnClientClicks can be set from code-behind depending on which validation groups I want to deal with right now.
Finally, to combine validation summaries, see the javascript here: Page_ClientValidate() with multiple ValidationGroups - how to show multiple summaries simultaneously? (with some tweaks).
Net very elegant, but probably gives the most control.
I am faced with this issue too - I have:
Multiple ValidationGroups triggered by different buttons
Validations that need to take place in both groups (in my case RequiredFieldValidators)
Adding multiple validators works as above until you enter and then subsequently blank out a field - you get both messages. My workaround is as follows:
Overwrite the IsValidationGroupMatch JavaScript method to allow for comma seperated values in the ValidationGroup property:
function IsValidationGroupMatch(control, validationGroup) {
if ((typeof (validationGroup) == "undefined") || (validationGroup == null)) {
return true;
}
var controlGroup = "";
if (typeof (control.validationGroup) == "string") {
controlGroup = control.validationGroup;
}
//return (controlGroup == validationGroup);
var controlValidationGroups = controlGroup.split(",");
return (controlValidationGroups.indexOf(validationGroup) > -1);
}
Then in the ASP you add:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ValidationGroup="VG1,VG2" Display="Dynamic">
Text box is required
</asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Validate VG1"
OnClick="Button1_Click" ValidationGroup="VG1" />
<asp:Button ID="Button2" runat="server" Text="Validate VG2"
OnClick="Button2_Click" ValidationGroup="VG2" />
This works on the client, but on the server you would need to add custom line(s) of code to ensure the controls listed as needing to be validated by both are checked:
// controls listed as part of ValidationGroup 'VG1' will have had their
// validation tested, ones listed as 'VG1,VG2', 'VG2,VG1' etc would not
protected void Button1_Click(object sender, EventArgs e)
{
Page.Validate("VG1,VG2");
if (!Page.IsValid)
return;
// do something
}
This way the validation controls are only needed to be added once but can be implemented for multiple ValidationGroups. It's really only a workaround/hack that works on the client, the extra checks on the all-important server side validation will need to be done manually each time.

ASP.net Custom Validator message not displaying

I have a div which acts like a modal popup. Inside that, I need a validation for which I setup a custom validator. But the message doesn't get fired, though the alert box does.
My code:
if ((oldFromTime <= newFromTime) && (oldToTime > newFromTime)) {
alert("Choose time ahead of the ones saved earlier.!");
arguments.IsValid = false;
}
else {
arguments.IsValid = true;
}
And my custom validator
<asp:CustomValidator id="cboToTimeMins_CustomValidator" ControlToValidate="cboToTimeMins" ClientValidationFunction="validateTime"
Display="static" ErrorMessage="Selected time range falls in the range of the ones saved earlier...! Choose another." runat="server" ValidationGroup="Timetable"/>
cboToTimeMins is my dropdown box, and I need to set the validation message based on the value selected from it.
Is there something wrong in my code?
P.S. I am in need of only CLIENT SIDE validation.
Here's my solution. I removed the custom validator for the Dropdown and added it to a button instead. Also, I removed the alert message in the Javascript function.
Here's my example solution
<td class="normal">Price<span class="required">*</span></td>
<td class="normal" colspan="6">
<asp:TextBox ID="txtPrice" CssClass="text" Enabled="true" runat="server" MaxLength="10" Width="100px" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtPrice"
ErrorMessage="* Please Input Your Price" Display="Dynamic" ValidationGroup="hdrValidation"/>
</td>
And you need to validate
Page.Validate("hdrValidation")
If Not Page.IsValid Then Exit Sub

Make the container of a validation summary visible when the validation summary becomes visible

I have the following markup. The errorPanel was first only used to show server side exception messages, and works fine like that. Now I'd like to incorporate my validation summary into that same errorPanel.
<asp:Panel ID="errorPanel" runat="server" CssClass="error" Visible="false">
<div style="float: right;">
Close</div>
<asp:Label ID="errorLabel" runat="server"></asp:Label>
<asp:ValidationSummary ID="validationSummary" runat="server" EnableClientScript="true" />
</asp:Panel>
<fieldset>
<legend>Create New Role</legend><asp:Label ID="newRoleNameLabel" runat="server" AssociatedControlID="newRoleNameText">Role Name:</asp:Label>
<asp:TextBox ID="newRoleNameText" runat="server" Width="100px"></asp:TextBox>
<asp:RequiredFieldValidator ID="newRoleNameRequired" runat="server" EnableClientScript="true" ControlToValidate="newRoleNameText" Display="Dynamic" ErrorMessage="Please enter a role name.">*</asp:RequiredFieldValidator>
<asp:Button ID="createButton" runat="server" Text="Create" OnClick="createButton_Click" />
</fieldset>
My problem now is that the required validation happens client side, and I want to keep that, so I have no server side opportunity to make errorPanel visible, in order to make the validation summary visible.
I see I have two options: Do validation server side, and use my code there to make the panel visible, or hook into the client side code somehow and catch an event there when the summary should be made visible, and then also make the errorPanel visible. How could I go about the latter?
Here is an approach which is really not recommended, but I had fun writing it, and it might lead you to some zany ideas!
(p.s. I am using jQuery to make life easier)
Take the Visible="false" off your asp:Panel, we'll do it all client side.
<asp:Panel ID="errorPanel" runat="server" CssClass="error">
Now, at document ready time we will hide the panel, and mess with ASP.NET's validation code.
$(document).ready(function () {
// This is more like it!
$("#<% =errorPanel.ClientID %>").hide();
eval('ValidatorCommonOnSubmit = ' + ValidatorCommonOnSubmit.toString().replace('return result;', 'myValidatorHook(result); return result;'));
});
That eval takes the ValidatorCommonOnSubmit() function which is generated by the ASP.NET validators, and modifies it in place so just before it returns its result, it calls myValidatorHook() with that result.
(see this StackOverflow question for where I got the idea)
Now, our hook:
function myValidatorHook(validated) {
if (validated) {
$("#<% =errorPanel.ClientID %>").hide();
}
else {
$("#<% =errorPanel.ClientID %>").show();
}
}
Simple enough - if the validator returned true (page validates), hide the panel; if it returned false (page did not validate), show it.
Use at your own risk! If the JavaScript generated by the ASP.NET validators changes, this will break horribly - but I did test it in ASP.NET 2.0, 3.5 and 4.0, and it worked the same in all three.
I had a similar problem where I had a containing div around a set of ASP validation fields, I wanted to only show the container if there was an error to show.
I used jQuery to hide the container as per Carson63000's answer, but then used jQuery to look at the visibility of the errors and show the container again if something was visible.
jQuery(function () {
jQuery(".checkout-validation").hide();
var show = false;
jQuery(".checkout-validation span").each(function () {
if (jQuery(this).css('display') != 'none' && jQuery(this).css('visibility') != 'hidden') {
show = true;
}
});
if (show == true) {
jQuery(".checkout-validation").show();
}
});
The only clarification other clarification I would add is that standard validation fields are set to visibility: hidden by default and Display="Dynamic" validations are display: none
Old question, but anyway.
I found one simple and clean solution to this. No server-side, no javascript needed.
You can simply put your content of errorPanel in HeaderText of ValidationSummary Control.
Like said on MSDN site:
The HeaderText property is not HTML encoded. Therefore, HTML tags can
be included in HeaderText.
Your example:
<asp:ValidationSummary ID="validationSummary" runat="server" EnableClientScript="true" CssClass="error"
HeaderText='<div style="float: right;">Close</div><span ID="errorLabel" runat="server"></span>'/>
<fieldset>
...
And PLBlum also nailed it on Microsoft asp.net forum:

Enable/disable RequiredValidator on client-side / CustomValidator not firing

I've got a drop-down where the user selects a Country. It is a required "field".
Next to it, there is a textfield named State. If the user selects US, then the field State is required. If the user selects e.g. Sweden, the State is not required, since Sweden has no states.
Example code:
<asp:DropDownList runat="server" ID="Country"></asp:DropDownList>
<asp:RequiredFieldValidator ControlToValidate="Country"
runat="server" Display="Static" ErrorMessage="Required field" />
<asp:TextBox runat="server" ID="State"></asp:TextBox>
<asp:CustomValidator ClientValidationFunction="DoesntGetFiredIfStateIsEmpty"
runat="server" Display="Static" ErrorMessage="Required field" />
<!-- SO, RATHER THIS TOGETHER WITH CONDITIONAL FIRING -->
<asp:RequiredFieldValidator ControlToValidate="State"
runat="server" Display="Static" ErrorMessage="Required field" />
My question to you is: How can I make this CustomValidator fire validation when it is empty?
Or put simplier: How can I make a RequiredValidator fire conditionally?
Or simplest: How can I enable/disable a RequiredValidator on client-side?
Try doing this with javascript to enable and disable validators
ValidatorEnable(RequiredFieldValidatorId, false);
Check out this question that I answered.
Asp.net has a client side javascript function to manage the validators, the "ValidatorEnable" function,
ValidatorEnable(RequiredFieldValidatorId, false);
you can call it simply using javascript, you must send the validator object to the function (not only its id).
if (x==y) {
ValidatorEnable($('#<%=rfvFamily.ClientID %>'), false);
} else {
ValidatorEnable($('#<%=rfvFamily.ClientID %>'), true);
}
or
if (x==y) {
ValidatorEnable(document.getElementById("<%=rfvFamily.ClientID %>", false);
} else {
ValidatorEnable(document.getElementById("<%=rfvFamily.ClientID %>", true);
}
full documnet on:
http://msdn.microsoft.com/en-us/library/Aa479045#aspplusvalid_clientside
another way is to Set in your DropDownList CausesValidation="false" to avoid that the validators block a postback when you change the DropDownList entry.
(*) Remember this function is for client side, for disabling validator in server side, you must to disable validator on page postback too.
if (IsPostBack){
if (x==y) {
rfvFamily.Enabled = false;
}
}

Resources