Adding javascript from code breaks the validation on page! How to handle it?
What I have is button that开发者_如何学Python should open another page only if textbox length is 8. Javascript must be added from code because it does not simply calls the bla.aspx, it's more like bla.aspx?id=4&code=234 etc etc...
I have this code on server side
button.Attributes.Add("onclick","javascript:window.open(bla.aspx)");
on client side i have
<asp:TextBox ID="policyNumberTxt" runat="server" MaxLength="8" CausesValidation="true"></asp:TextBox>
<asp:RegularExpressionValidator ID="policyNumberTxtRev" runat="server"
ControlToValidate="policyNumberTxt" ErrorMessage="Length must be 8."
ValidationExpression="{.{8}.}" ValidationGroup="bla" Display="Dynamic"></asp:RegularExpressionValidator>
<asp:Button ID="printBtn" CssClass="button" Text="Print" runat="server" CausesValidation="true" ValidationGroup="bla" />
What happens is that when I click the button page bla.aspx opens, and even postback is trigered. Validator is showing the message, but page is opened and postback trigered.
How to handle this? Validation is broken...
Thanks..
To prevent submitting the form add "return false;"
button.Attributes.Add("onclick", "window.open('bla.aspx'); return false;")
but that would also prevent the form from doing postback at all!
note that the passed url should be enclosed in quotes.. And you don't need the "javascript:" prefix as 'Pointy' said
I think the validation regular expression should be more strict to allow only letters and numbers like this
ValidationExpression="[A-Za-z0-9]{8}"
Try putting the client click logic in the onsubmit of the page's form instead?
Found answer here
this.cmdSubmit.Attributes.Add("onclick","if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate();if(Page_IsValid){window.open('upload_status.aspx','_blank','width=250,height=250');}");
精彩评论