views:

371

answers:

2

The following .NET 3.5 code, placed in an aspx file, will trigger a JavaScript error when the page is loaded (for users who have JavaScript enabled):

<noscript>
    <asp:TextBox ID="txt" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="txt_RequiredFieldValidator" runat="server" 
      ControlToValidate="txt"></asp:RequiredFieldValidator>
    <asp:Button ID="btn" runat="server" Text="Button" />
</noscript>

The error happens because the JavaScript generated by the ASP.NET validator control does not contain a null check on before the second code line below:

var ctl00_body_txt_RequiredFieldValidator =
  document.all ?
    document.all["ctl00_body_txt_RequiredFieldValidator"] :
    document.getElementById("ctl00_body_txt_RequiredFieldValidator");

ctl00_body_txt_RequiredFieldValidator.controltovalidate = "ctl00_body_txt";

Can anyone suggest a workaround to this?


Footnote: Why am I doing this? For my non-JavaScript users I am replacing some AJAX functionality with some different UI components, which need validation.

A: 

The javascript is looking for an element contained in the noscript? AFAIK there's no clean way to detect script support from the server side.

I think you'll need to build in a redirect (I've seen this done with a meta-refresh in a header noscript if you don't mind a validation failure) to push noscript users to a "please turnscript on page" or do some surgery to loosen up the validation/control binding which may take some amount of wheel reinventing. This is one of those areas where asp.net's tight coupling between controller and view really punishes.

annakata
+2  A: 

You should add the following to the RequiredFieldValidator:

enableclientscript="false"

Seeing as you are using these in <noscript> tags, there is no point in supplying client side vaildation of the controls - they are only going to display if JS is turned off.

This will force the validation to happen (automatically) on the server side for you.

Just make sure you call "Page.IsValid" before you process the response.

See BaseValidator.EnableClientScript for more details.

Zhaph - Ben Duguid