Server side validation affecting client side validation

Hi there

I have some client side validation that is working fine and enables/disables buttons based on user selections. This works great. However, when I perform server side validation using custom validators (like checking if the user has entered < HTML > tags or decimals in the integer boxes) and the server side validation returns isValid = false then all of the JavaScript validation that I've already done when the user clicked each control is lost. I don't understand why the enabled/disabled state of the control is not maintained.  What is calling the JavaScript refresh?

 

Thanks

0
globrite
7/3/2008 9:45:50 PM
asp.net.web-forms 93655 articles. 5 followers. Follow

12 Replies
1661 Views

Similar Articles

[PageSpeed] 29

Are you saying that the client-side validation is not preventing a postback?  If so then there's an error in your custom validator's javascript.  Any error that occurs during validation usually prevents the any further processing which is what also prevents the execution of the script which stops the postback. 


Rob Mills

www.dotnetadvisor.com
0
DotNetAdvisor
7/4/2008 12:29:29 AM

Thanks for replying.

No, the client side validation is working in that I don't see a complete refresh of the page and post back. What I see are the validation messages appearing if a mistake is present. However, other JavaScript that I have on the page is also affected. I have some client side JavaScript that opens and closes radiobuttonlists based on user selections - for example, if they select that they had no previous illnesses then the buttons on type and condition and free text comments grey out and become disabled. However, upon server side validation using custom validators and not even necessarily on these particular controls, after the validation happens the buttons/textareas etc I have disabled with JavaScript re-open. The page is not refreshing or posting back so why would the buttons open up?

Thanks

0
globrite
7/4/2008 9:52:00 AM

Can you post both your javascript and your server validation? 


Rob Mills

www.dotnetadvisor.com
0
DotNetAdvisor
7/4/2008 11:41:35 AM

Ok, it is quite complicated; I hope you are able to understand how it all happens. However, there are many of these validators on my ASP page so I've only shown a sample.

The JavaScript to enable/disable

function enableControlsOnSelection()

{

var numberOfControls = enableControlsOnSelection.arguments.length;

// This should always be a RadioControlList used to base our selection criteria upon

var tableBody = enableControlsOnSelection.arguments[0].childNodes[0]; for (var i=0;i<tableBody.childNodes.length; i++)

{

for (var j=0;j<tableBody.childNodes[i].childNodes.length; j++)

{

var currentTd = tableBody.childNodes[i].childNodes[j];

var listControl = currentTd.childNodes[0];

 

if (listControl.checked)

{

if (listControl.value == "Yes" || listControl.value == "Maybe")

{

// User has selected the "Yes" radio button

// Enable controls

// Note: We start at 1, as the 0 element is our radio control list that

// we have used above to determine whether the user has selected Yes or No

for (i = 1; i<numberOfControls; i++)

{

enableControl(enableControlsOnSelection.arguments[i]);

}

break;

}

else if (listControl.value == "NO" || listControl.value == "Not Yet")

{

// User has selected the "No"  radio buttons

// Disable and clear controls

for (i = 1; i<numberOfControls; i++)

{

disableControl(enableControlsOnSelection.arguments[i]);

}

break;

}

}

}

}

}

function disableControl(control) {

// Try to disable complex list control type

disableListControl(control, true);

clearListControl(control);

 

// Try to disable simple control type

control.disabled = true;

control.value='';

}

function enableControl(control) {

// Try to enable complex control type

disableListControl(control, false);

 

// Try to enable simple control type

control.disabled = false;

}

 

The  ASP that adds the JavaScript to the control:

public static void enableControlsOnSelection(RadioButtonList rb, WebControl control)

{

String radioButtonID = "document.getElementById('" + rb.ClientID + "')";

String jScript = "enableControlsOnYesSelection(" + radioButtonID;

// Extract the ID for the control you wish to enable and append it to the javascript argument list

// The javascript function will handle the variable number of parameters

String controlID = "document.getElementById('" + control.ClientID + "')";

jScript += "," + controlID;

jScript += ");";

rb.Attributes.Add("onclick", jScript);

}

The code that calls the method on the ASP page:

ClientSideValidation.enableControlsOnSelection(rblA, rblB);

 

A sample of the server side validation:

protected void TextboxValidator_ServerValidate(object source, ServerValidateEventArgs args)

{

if (Comments.Text.Contains("|"))

{

args.IsValid =
false;

 

}

else if (Comments.Text.Contains(System.Environment.NewLine))

{

args.IsValid =
false;

}

else if (Comments.Text.Contains("<") || CommentsCOL.Text.Contains(">"))

{

args.IsValid =
false;

}

}

0
globrite
7/4/2008 1:35:51 PM

Oops!

String jScript = "enableControlsOnYesSelection(" + radioButtonID;

Should be

String jScript = "enableControlsOnSelection(" + radioButtonID;

1
globrite
7/4/2008 1:53:51 PM

Maybe I'm not totally understanding what you're trying to accomplish but it seems to me that your validator could be replaced with a regularexpressionvalidator.  If the problem had to do with your custom validator then that would solve it.  Have you tried using that?


Rob Mills

www.dotnetadvisor.com
0
DotNetAdvisor
7/5/2008 3:56:16 PM

Hi there

The custom validator I showed is the simplest one I had - there are many others that do quite complex things like validate whether or not some fields are required based on user selection. Although a range validator might work for one, it would not work for them all.

In any case, both would return isValid = false if the validation was not met, and I think I would be in the same position with either server validator. Either would cause the page to return with a validation error and re-open my other JavaScript events on the page.

Just to refresh what I'm doing, I have two methods to validate user input - JavaScript to open/close web controls based on user selections (and therefore the JavaScript events are tied into the webcontrols) and also server validation to check things like the required fields (based on user selections) etc. The JavaScript works fine and the server side works fine independently, however, when the server side validation is triggered (isValid = false) then the page appears with the server validation messages, as expected, but the other events from my own JavaScripts need to be re-fired again. I need to re-click these buttons again to trigger the buttons' onclick events.

I don't understand how this can happen without a full post back. I have a JavaScript countdown timer on the page that resets on the window.onload event and during server side validation this counter is not reset - therefore I know that the Window's onload event is not called.

Any ideas?

0
globrite
7/7/2008 9:12:53 AM

I would separate the javascript that is used to disable controls from the javascript that is used for validation.  Because any postback will then require the javascript to run again when the page loads in the browser.  Then you'll need to come up with some kind of way to maintain the state using javascript.  Probably the best way is using hidden fields.

Now are some of your validators only validating on the server?  In other words did you not provide client validation for them?
 


Rob Mills

www.dotnetadvisor.com
0
DotNetAdvisor
7/7/2008 11:23:56 PM

Some thoughts:

1. If you set the disabled attribute on the client-side to true, the browser does NOT send a value back to the server for that control. (Its an Http behavior, not ASP.NET).

2. The state of the disabled attribute is never transferred to the server. Only the value attribute of each <input>, <textbox> and <select> tag gets transferred.


--- Peter Blum
Creator of Peter's Data Entry Suite (formerly Professional Validation And More and Peter's Date Package) and Peter's Polling Package
www.PeterBlum.com
0
PLBlum
7/8/2008 6:00:44 PM

I'd be interested to find out if anyone has a solution to this.

I have a similar problem.  My page has some textboxes, radio buttons, etc that are enabled and disabled by javascript depending on what the user clicks on.

For example on a page that allows users to change their contact details (residential, postal, email, phone):

By default when the page loads, the fields for the user's address are disabled (by javascript invoked onload).

If they click on the Change Address checkbox, the javascript then sets the fields enabled and they can enter in their new details.

However if they just click on the submit button without changing anything, or if there's something wrong with the data entered, then the validation (RequiredFieldValidator/CompareValidator/etc) posts an error message.  All of the fields on the page are reset to be enabled when the page refreshes.  The OnLoad function does not appear to be invoked.

0
daviessi
10/24/2008 12:48:35 AM

daviessi:

I'd be interested to find out if anyone has a solution to this.

I have a similar problem.  My page has some textboxes, radio buttons, etc that are enabled and disabled by javascript depending on what the user clicks on.

For example on a page that allows users to change their contact details (residential, postal, email, phone):

By default when the page loads, the fields for the user's address are disabled (by javascript invoked onload).

If they click on the Change Address checkbox, the javascript then sets the fields enabled and they can enter in their new details.

However if they just click on the submit button without changing anything, or if there's something wrong with the data entered, then the validation (RequiredFieldValidator/CompareValidator/etc) posts an error message.  All of the fields on the page are reset to be enabled when the page refreshes.  The OnLoad function does not appear to be invoked.

 

Take a look at this article I wrote on my blog about performing conditional validation:

http://www.dotnetadvisor.com/Blog/ConditionalValidation.aspx 


Rob Mills

www.dotnetadvisor.com
0
DotNetAdvisor
10/24/2008 2:38:17 AM

 Hi Rob,

Your article is close to what I am looking for, but not quite.  The problem is not with the validation as such.  The validation is working correctly and catching all the things I want it to.

The problem is what happens when the validation returns an error.  The page appears to refresh, but the javascript function that should be called as part of the OnLoad() is not being called.  This javascript checks the control checkboxes and sets fields disabled/enabled as required.

When the page refreshes with the validation error message, half the fields on the page are enabled when they shouldn't be.

0
daviessi
10/24/2008 2:54:40 AM
Reply:

Similar Artilces:

client side validation vs server side validation
hello  i see a web form that consists of three controls :textbox,requiredfieldvalidator that weired to the textbox and a button within the click event of the button there is the following: if page.isvalid then response.redirect("Page is valid") else response.redirect("Page is not valid") end if according to my understandings: when the user does not fill anything in the textbox and then clicks the button the the page will not be submitted (i.e no request to the page will be happened or no postback will be happened) then no server event will be happened so it is sure when the us...

Server Side Validation vs Client Side Validation
If your page is using client side validation for required fields, expressions, etc.     What are the benefits or disadvantages of using 'extra' server side validation for max lengths, parsing, etc? Both have their Advantages and Disadvantages... so give this a read http://www.dotnetexpertsforum.com/viewtopic.php?t=172 Regards,Vinz"Code, Beer and Music" that's my way of being a programmer!How to get your Forum Question Answered | Blog | CodeASP.NET hi there, advantage: because you are using javascript some browsers for any reason may not sup...

avoiding redundant server-side validation after client-side validation
I see an inaccurate validation behavior on my asp.net (2.0) form. The EnableClientScript property of my validation control is set to True by default, so it performs the validation on clientside. But as soon as this occurs, it also performs the server-side validation, so the page refreshes. When the validation error occurs on clientside, it should not do the validation on serverside (I'm not calling Page.Validate() or doing Page.IsValid). In my past experience, asp.net handled this automatically, but I guess it's not always the ca...

form double validation- server side and client side
Hi! I would like to make a server side validation after calling a js function that makes the client-side validation. I do not understand couple of things: 1. Do i need a server side button or  a simple HTML submit button in order to call both of the tests? 2. How do i call a server side function which is written in csharp  after i finish my JS validation (the submit  button is calling the JS function for validation first.)- is it possible to call it directly from a js function? 3. I know that my toolbox on asp.net  contains validation controls who probably are b...

Validation Controls in .NET ( Client side or server side?)
 i have a very basic question. We have all these validation controls in asp.net ( required field, range validator and others)..my question is the required field validator is a server side control. So does that mean that it does a post back?..is it client side or server side control  The only controls that post back are buttons and other inputs where you set AutoPostback="True", such as a dropdownlist or a textbox.  Another way of posting back is using an UpdatePanel and placing a trigger in it for a specified control and/or event. All controls are considered clien...

validation, is it better to have client side or use server side validator controls
 Hi All. I want to do validation on text boxes etc. Is it better to do client side validation or just use the server side validation controls?   Hi!  If for server side controls you mean RequiredFieldValidator, CompareValidator, RegularExpressionValidator, etc.. i can tell you that they use client and server validation. For instance if you use a RequiredFieldValidator, on the client will be a validation, but on the server this condition will be evaluated again. Probably one of the objetives of this is deal with client with javascript disabled. Of course I ...

client side and server side validation
http://samples.gotdotnet.com/quickstart/util/srcview.aspx?path=/quickstart/aspplus/samples/webforms/validate/validator8.src&file=CS\validator8.aspx&font=3 i am trying to do custom validation something similar to the above. I hv done the Severvalidate method in the code behind. What about the client validation? do i do it in code behind or in javascript as shown? The goal is to add text like this to the page:<script language='javascript'>function MyFunction(src, args){  // your logic to set args.IsValid here}</script>ASP.NET doesn't care if you typed it directly in...

Client side or server side validation???
I have multiple usercontrols each displayed by pressing a button and then change the apperance to a new user control and so on. I have to check that almost every field in this user controls have a value entered, and then indicate (e.g. with a red star) those textboxes that does'nt have a value entered. How should I do this in the best way, client side or server side with some validator? I have in mind that when using a server side validator, it may dissapear when making a postback. But I'm not sure, and I assume there is a way to come around this problem?What do you all say? Client side or s...

Validations client side or server side ???
Where should the validations (Required field, range, etc.) be done in an web page client side or server side?  As per my knowledge most of the validations are on client side using javascript, unfortunately it won't work if someone has disabled their browsers javascript option. what do we do in this case? Any suggestion please. Both... Client-side for rich client experience. Server-side for data validation and for clients who have disabled javascript. *Always* validate on the server side. You will still get the benefits of client-side validation on browsers setup to handle th...

SERVER SIDE DATA VALIDATION ON CLIENT SIDE
I wonder if this is the right forum to post this question because it is an issue about both server and client side processing. I am developing a web application (online store) which will run in a hosting company. Users accessing this app will be able to place orders with one limitation; the store has a schedule to accept orders. For example, it can be open from 8AM to 10PM and/or it can be closed on Mondays. I just can't validate time and/or day directly because time zone may lead to wrong results. So I thought about getting the schedule information, which is saved in my database, ...

Disabling Client Side and Server Side Validation
I have a page which contains a User ID and Password field which have RequiredFieldValidators against them. The page can also load a User Control which contains another field which also has a RequiredFieldValidator against it. When I submit the form I use the ValidatorEnable function to disable the validator, on the User Control Page, when the user is signing in. This works fine on the client side but the page fails on the server side as I presume it does not know that I have disabled the control from the client side. Can anyone tell me the best way to solve this problem. Thanks M...

When do the validators kick in? Are they server side or client side?
 Hello,I am confused. I was under the impression that asp.net validators work on the client side.But I was confused when I set the enabled property of validator to false and then the validator did not work. (RegularExpressionValidator1.Enabled = false;)But the other confusing thing to me is that if the validators  work on the server side then when don't i see the page refresh like on other postback events? Kindly throw some light.Thanks!   Validators always work on the server side (assuming they're enabled), but also work on the client side if EnableClientScript is t...

Client-side validation works, but server-side does not.
Hey all,I have got this text box control on my webform, which has two validators.. 1. RegularExpressionValidator and 2. CustomValidator.Now, RegularExpressionValidator control works if I enable client-script. But somehow it does not work for server-side validation. Any idea why this is happening? This happens to another textbox control on other web form as well which has similar coding. So, to enable the validation at present I can only do client-side validation I guess.  1 <TD> 2 <anthem:TextBox id="txtDatePlannedSurgery" CssClass="aspText" Runat="server" AutoCal...

Validation Conrols: Client Side or Server Side?
Hi Folks, I am just wondering if the validation controls, use javascript...or server side code behind...Clearly, I would prefer it be server-side, because i'm concerned that a potential evil-doer could by-pass the validation, by turning off JS.If the validation controls use JS --- can someone refer me to proper server side validation techniques (VB). Thanks, - Joel    "The truth is rarely pure and never simple."- Oscar Wilde, The Importance of Being Earnest ASP.NET validation controls always use server-side validation, with additional client-side...

Web resources about - Server side validation affecting client side validation - asp.net.web-forms

Cross-validation (statistics) - Wikipedia, the free encyclopedia
is a model validation technique for assessing how the results of a statistical analysis will generalize to an independent data set. It is mainly ...

Serena Williams eyes history, Caroline Wozniacki craves validation in women's US Open final
As Serena Williams eyes another slice of tennis history, Caroline Wozniacki is craving validation with a watershed US Open final triumph on Sunday ...

Travers Duncan asks High Court to strike down ICAC validation laws
ICAC could be sent back to the High Court as a challenge to new laws validating corruption findings looms.

Adam Scott proclaims Texas win as validation of No.1 ranking
... No.1 golfer, beating American Jason Dufner in the third hole of a play-off at the Colonial event. "It's a good feeling and maybe some validation ...

Hollande to sign gay marriage bill after Constitutional Council's validation
Hollande to sign gay marriage bill after Constitutional Council's validation People's Daily Online ... 26, 27, 28, 29, 30, 31. Jan, Feb, Mar, ...

Marketers, Get Ready for the 'Validation Era'
The public brands included has been engaging in a "friends" arms race. But there are signs that we know we overdid it.

Validation and Uncertainty
What an extraordinary conversation I had recently on Twitter. It started with Neil Killick’s statement that we should not consider our stories ...

Nvidia Icera 410 LTE Modem Passes AT&T Network Validation
... Today's news is a small step and logical precursor toward both goals, Nvidia's Icera 410 LTE and HSPA+ baseband has passed AT&T's network validation ...

Ting’s Q1 Subscriber Growth Suffers from Sprint’s New Unlocking Validation Process
Back in February, Sprint updated the process it uses to validate unlocked devices that customers want to utilize on other carriers or one of ...

[Android M Feature Spotlight] Stricter APK Validation Now Actually Checks If All Of An APK's Files Are ...
While you might file this one under "really? We weren't doing this already?" if you're a security expert, Google has added stricter validation ...

Resources last updated: 12/28/2015 1:34:20 AM