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.
You should add the following to the RequiredFieldValidator:
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.