Only enable RequiredFieldValidator when parent element is visible? - c#

I have an asp.net webform with a few Panels that each have several textboxes inside of it. I am currently hiding or displaying the panel using jQuery based on which item in a DropDownList is selected.
I have run into an issue where the required field validator is still firing even when the elements it is attached to is not showing because it's parent panel has display: none.
Is there any way to disable the RequiredFieldValidator when the element it is attached to is not showing because of CSS?
I know that if set Visible=false on the server side the elements wouldn't render at all, but I would prefer to keep the show/hide logic on the client side for user experience reasons.

I agree that a custom validator would be best, but if you do need to do it on the client side, you can use the ValidatorEnable function.
ValidatorEnable(document.getElementById("<%= RequiredFieldValidator.ClientID %>"), false);
(Note that I have never actually tried this myself, but I have heard of it successfully being used to disable validators on the client side.)

As this thread says, you can use that function. So modify your method like below
function cbSearchOption_SelectedIndexChanged(sender, args) {
var x = document.getElementById('cbSearchOption').value
if (x == 'Date')
{
ValidatorEnable($get(‘<%=DateValidator1.ClientID %>’), true);
document.getElementById('test').style.visibility = 'visible';
}
else
{
ValidatorEnable($get(‘<%=DateValidator1.ClientID %>’), false);
document.getElementById('test').style.visibility = 'hidden';
}
}

Related

How to hide controls In Ext.net with javascript or in direct events

The problem is simple, I have ids of the contols and i want to show/ hide them on some event.
Actually the problem is i have a direct event on dropdown change i have to hide some controls based on some cases
the code for the direct event is
foreach (Control oControl in ProductConfiguration.Controls)
{
string strName = oControl.GetType().Name;
oControl.Visible = false;
DataRow[] drIRows = dtInfo.Select("ControlId='" + oControl.ID + "' AND ProductGroupId='" + CboProductGroup.Value + "'");
if (drIRows.Length > 0)
oControl.Visible = true;
}
but the visible property doesnt works with direct events, so my idea was to use javascript instead, can anyone help.
After rendering to the page, visibility cannot be modified since the "visible" property refers to whether or not the client even receives the object to be able to place it on the screen.
I suggest two things if you would like to dynamically change this.
use Hidden="true" rather than Visible = "false" on the page
change your code behind to affect the Hidden property: oControl.Hidden=false;
If you use Hidden property, the client still receives the control to render (it simply doesn't display if set to true), and it can then be quite easily changed.
Please use the Hidden property instead.
The difference is explained here.
Also you can use the Show/Hide methods.

ASP.NET Custom Server Control not disabled inside a Panel that is disabled

I have written a custom ASP.NET Server Control. When I am rendering the control, I check the this.Enabled property to determine if I should add the disabled attribute to my tag (extract of code below). Unless I specifically set the Enabled flag, this value is True regardless of the state of the panel it is in.
output.AddAttribute(HtmlTextWriterAttribute.Type, "text");
if (!this.Enabled)
{
output.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
}
output.AddAttribute(HtmlTextWriterAttribute.Value, this.DisplayName);
output.RenderBeginTag(HtmlTextWriterTag.Input);
output.RenderEndTag();
Standard server controls like textboxes etc, behave as expected in this scenario and are disabled.
What is the pattern that I must implement to be able to check if the control is actually to be disabled or not? Do you have to check the parent(s) to see if any of them are a Panel and then see if they are enabled? Seems very inefficient if that were the case.
Thanks
Mark
Just found it.
Needed to modify the code to:
output.AddAttribute(HtmlTextWriterAttribute.Type, "text");
if (!this.IsEnabled)
{
output.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
}
output.AddAttribute(HtmlTextWriterAttribute.Value, this.DisplayName);
output.RenderBeginTag(HtmlTextWriterTag.Input);
output.RenderEndTag();

Code-behind check to see if a control has been set to display: none?

I currently have a control that is being hidden on my server side using dropdown.hide();.
hide() is a server-side method I created to hide my methods, e.g.
control.Style["display"] = "none";
How can I tell, on the server-side, if my control is hidden or not?
I'm guessing you don't mean just doing:
if (control.Style["display"] == "none") { .... }
And that you want to know after a postback? If that's the case, then you can't do it, unless you store the fact it's hidden in a hidden input or something like that, using JavaScript.
Just check if control.Style["display"] == "none"
If it is changed on the clientside you have to save the state so it will be sent by the POST action. You can save the state in a hiddenfield or using AJAX?

javascript viewstate problem

I have a situation that I am stuck with, and hoping someone can help. I am building a .NET/C# web application in which I have a tabbed panel layout, and when the user clicks on each of the tabs the display panel is updated using javascript to hide and show some divs. None of these clicks cause postback, it is all client-side, so I can't use viewstate or session.
What I want to do is somehow remember which panel was last visible when the page is refreshed, yet without posting back to the server I am unsure how to do this. I have tried a hidden field but obviously its value is reset every time because the form is never submitted. I do know that I can achieve this using cookies but its a little annoying to implement for such a (seemingly) trivial operation ... but maybe this is the only way?
Does anyone have any more elegant solution to this problem?
Using a function like this to show and hide tabs):
function makeCurrent(tab) {
if (tab.title == 'Manage orders') {
document.getElementById('panelOrders').style.display = "block";
// Hide others
document.getElementById('panelAccounts').style.display = "none";
document.getElementById('panelProducts').style.display = "none";
document.getElementById('panelSettings').style.display = "none";
// Remember last viewed panel
document.getElementById('hdnCurrentlyViewing').value = "orders";
}
The panels are just divs with style.display controlling their visibility. Not sure if its useful to post HTML code because its fairly self explanatory ...?
You can make this happen without a postback is to make an AJAX call from Javascript where you tell your server what the current panel is as you switch it.
I prefer using a framework like JQuery or Prototype to help make these AJAX calls myself.
I think Hidden field will be the best option. have you tried ASP:HiddenField? It can be accessed across postbacks.
But if you still have some reservations with postbacks and hiddenfield you can also use cookies from JS http://techpatterns.com/downloads/javascript_cookies.php this is helper lib for cookies manipulation within JS.
Regards.

How can I validate that several textboxes contain data when I click submit?

I have 10 defined textboxes with strings.
I have to check all if they are not empty while clicking ok button
whats the cleanest way to check them all and when function is at end. each checkbox which was empty to give this a specific CSSclass. perhaps. ClassError. ( which highlights red)
I'm happy for answers.
I would add RequiredFieldValidators to them, as well as a ValidationSummary control.
edit: You can also add fancy AJAX effects with the ValidatorCallout from the AJAX toolkit.
edit: Validator controls also support client-side validation.
Using javascript or C#?
Javascript I will create an array of textbox and loop through it.
C# just go FindControl within a Panel or the Container of the text box and go something like this
foreach(Control C in ContainerID.Controls)
{
if ( C is TextBox )
{
if ( String.IsNullOrEmpty((C as TextBox).Text))
{
// Do things this way
}
}
}
Something like this would work on the client side using jquery:
$('input').filter(function(){return this.value=="";}).css("CSSclass");
edit: I just saw the C# tag, I'll leave this here for posterity though.
What you're doing might be simple enough to do easily with some custom javascript code, though I would say that in general the built in validator controls are both easier to use and more robust than a simple validation routine that someone might write. In addition to client-side validation, the validator controls also perform server-side validation to ensure that the data submitted is truly valid, in case someone has javascript disabled in their browser.
If validator controls are included on the page, then they will include some javascript functions that you can invoke, such as Page_ClientValidate(). I believe this will return a boolean telling you whether validation passed and will trigger the visual indicators that identify what the errors are. You can execute Page_ClientValidate('') to trigger only a group of validator controls; actually I think you must do that in order to trigger validation on any validator controls that have a value in their ValidationGroup property, as I don't think Page_ClientValidate() will trigger their validation logic.
There is a CustomValidator control that you can point to your own client-side function if you want, in case you do have some special validation logic that you can only implement through a custom javascript function. This is nice to use, because then your custom javascript function will be executed by the built-in validator framework along with any other built-in validator controls that you might choose to include on the page.
Side note regarding client-side validation: I suggest that you avoid doing the following to trigger validation:
onclick="return myValidationFunction();"
because if there is any other javascript code being injected into the onclick event, your return statement will prevent it from executing. So instead, I suggest doing this:
onclick="if(!myValidationFunction()) return false;"
That's bitten me enough times that I thought I'd just throw that out there. This problem is particularly noticeable if you have an ASP.Net button on which you've set the UseSubmitBehavior property to false, as it will cause the button to render as an HTML "button" control instead of a "submit" control, and as a result, executing a return statement, either true or false, will prevent the button from triggering a postback.

Categories

Resources