Server Side validations firing in one machine and not in another - asp.net

I have a page with 2 textbox control for account number and house number. Both the controls have required feild validators as well as regular expression. I have some server side validations too, that fires, only if the client side validations are passed.
The Problem is that, in my local dev VM, if I leave the textboxes blank and click the button, the client side validations fire. The same code is deployed to our Testing enviornment and on the testing site if I click the button leaving the textboxes as empty, both the server side as well as client side validations are fired.
I want the same behavior in testing enviornment also. i.e server side should fire only when client side validations are passed.
What is causing this behavior? I am little newbie to .net so excuse me if I am missing on some very fundamental concept here. The .net Version is 4.5 with Visual studio 2012
Code Account number:
<div id="textboxAccNumCss" runat="server">
<div class="form-group">
<asp:Label ID="lblAccontNumber" runat="server" Text="* Account Number"></asp:Label>
<asp:TextBox ID="txtAccountNumber" runat="server" class="form-control"></asp:TextBox>
</div>
<div>
<asp:RequiredFieldValidator ID="rfvAccountNumber" runat="server" ForeColor="Red" ValidationGroup="AccountValidation" ControlToValidate="txtAccountNumber" ErrorMessage="Enter Account Number"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rgxAccountNumber" runat="server" ControlToValidate="txtAccountNumber" ErrorMessage="Enter in Correct Format" ForeColor="Red" ValidationGroup="AccountValidation" ValidationExpression="\d{1,12}(-\d{1})?"></asp:RegularExpressionValidator>
</div>
</div>
Code for House Number
<div id="textboxHSnoCss" runat="server">
<div class="form-group">
<asp:Label ID="lblHouseNumber" runat="server" Text="*House Number"></asp:Label>
<asp:TextBox ID="txtHouseNumber" runat="server" class="form-control"></asp:TextBox>
</div>
<div>
<asp:RequiredFieldValidator ID="rfvHouseNo" ForeColor="Red" runat="server" ValidationGroup="AccountValidation" ControlToValidate="txtHouseNumber" ErrorMessage="Enter House Number"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rgxHouseNo" runat="server" ValidationGroup="AccountValidation" ControlToValidate="txtHouseNumber" ForeColor="Red" ErrorMessage="Enter in Correct Format" ValidationExpression="^[a-zA-Z0-9 #-/*]*$"></asp:RegularExpressionValidator>
</div>
</div>
Code for Button Click
<asp:Button ID="Button1" runat="server" Text="Continue" ValidationGroup="AccountValidation" OnClick="btnContinue_Click" class="btn btn-primary" />

Your first task should to make sure that client side validation is done successfully and then go for postback and server side validation. You could use the below js code to verify if the page is validated properly or not.
if (typeof (Page_Validators) != "undefined") {
if (typeof (Page_ClientValidate) == 'function') {
isPageValid = Page_ClientValidate("AccountValidation");
}
}
Based on the isPageValid value you could do stop or continue postback.

Related

How to fix validation summary message not getting refreshed when keep SetFocusOnError as true

I am using two asp.net validation controls 1. RequiredFieldValidator & 2. RegularExpressionValidator for my password textbox to validate the user input and set its display property to none so that valiadation message will only get displayed in validationsummary control.
when I click on submit button the validation get displayed as expected but when I use SetFocusOnError as true for both validators sometimes the validation message doesn't get refreshed for ex. if there is no text entered in the text box and click on submit button it display required field validation message but when enter any text and click on submit button it still display required field validation instead of RegularExpressionValidator validation message but when click submit button next time it propertly display
RegularExpressionValidator validation message
<asp:TextBox ID="txtPass" CssClass="form-control" runat="server" TextMode="Password"
meta:resourcekey="txtPassResource1" autocomplete="off"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPass" runat="server" SetFocusOnError="true" ControlToValidate="txtPass"
Display="None" ErrorMessage="Enter Password" ValidationGroup="submit"
meta:resourcekey="rfvPassResource1"></asp:RequiredFieldValidator>
<div class="password_error" style="width:auto;">
<asp:RegularExpressionValidator ID="rxvalPassword" runat="server" ErrorMessage="Password should be at least 6 characters in length. It should have at least one numeric and one special character from ~ ! # # $ & _ . * "
ControlToValidate="txtPass" SetFocusOnError="true" ValidationExpression="^(?=.*[0-9])(?=.*[~!##$&_.*])[A-Za-z0-9~!##$&_.*]{6,15}$"
ValidationGroup="submit" Display="none" meta:resourcekey="SpecialCharResource2" />
</div>
<div class="rows col-md-offset-5">
<div class="width12">
<asp:ValidationSummary ID="valnewuser" runat="server" ValidationGroup="submit" meta:resourcekey="valnewuserResource1" EnableClientScript="True" />
</div>
</div>
<div class="col-md-offset-6">
<asp:Button ID="btnSubmit" runat="server" OnClientClick="return ValidatePage();" CssClass="btn btn-primary" Text="Submit" OnClick="btnSubmit_Click"
ValidationGroup="submit" meta:resourcekey="btnSubmitResource1" />
</div>
Please do test it again as when I reviewed and tested your code, it worked perfectly fine.
The error showed as per validation. If still some anomaly happens, do show that exact code.

My modal window is not transferring values to vb.net codebehind

I am getting the username and password to run some scripts
<act:ModalPopupExtender ID="unixLoginMPE" runat="server" TargetControlID="rdoUnix"
PopupControlID="unixPanel" BackgroundCssClass="modalBackground" CancelControlID="unixCancel" OkControlID="unixSubmit"
/>
<asp:Panel ID="unixPanel" runat="server"
CssClass="modalPopup" align="center" Style="display: none">Unix Username: <asp:TextBox ID="unixName" ClientIDMode="Static" runat="server" />
<br />
Unix Password: <asp:TextBox ID="unixPass" runat="server" ClientIDMode="Static" TextMode="Password" />
<br />
<asp:Button ID="unixCancel" runat="server" Text="Cancel" />
<asp:Button ID="unixSubmit" ClientIDMode="Static" runat="server" Text="Submit" OnClientClick="enableRDO()" />
</asp:Panel>
In my codebehind, I'm doing something like this just to test if the values have passed.
Dim UNIXPASSWORD As String = unixPass.text
Dim UNIXUSERNAME As String = unixName.Text
MsgBox(UNIXCOMPUTERNAME)
MsgBox(UNIXUSERNAME)
MsgBox(UNIXPASSWORD)
I do reference a script to enable the radio button. I asked a question to help me with that issue, it is all resolved Radio Button won't stay check if I have a modal window open up when it is selected
<script type="text/javascript">
function enableRDO() {
var cancel = document.getElementById('rdoUnix');
cancel.setAttribute('checked', 'true');
};
</script>
For some reason the values are passing just fine in Google Chrome but not in IE. I've been at this for a few hours and don't know what else to try...or search for
EDIT:
I'm still trying to attempt this. I setup up dummy text boxes which I will hide later on if I can pass to them. I'm still very lost with this...
<asp:TextBox ID="dummyUnixName" runat="server" />
<asp:TextBox ID="dummyUnixPass" runat="server" />
If you aren't performing a postback or an AJAX call, nothing will be passed to the code behind.
During debugging, Console.WriteLine can be redirected to the output window in VS; in production, it's going to go nowhere. A logging solution is often appropriate for a web application which needs to know more of what happened than which page was requested by a user (IIS logs).

AutoPostBack on CheckBox control sometimes fails

If have the below markup.
<asp:checkbox id="chkTVLic" runat="server" text="TV Licence" oncheckedchanged="chkDocs_CheckChanged"
autopostback="true" CausesValidation="false" />
<asp:panel id="pnlTVLic" runat="server" visible="false">
<div class="toggle-item-link1 document-date">
<asp:panel id="pnlTVLicIssueDate" runat="server">
<p>
Please enter the date of issue
</p>
<div class="fm-req">
<asp:textbox id="txtTVLicIssueDate" cssclass="tb size2" runat="server" onblur="return true;"></asp:textbox>
<cc2:calendarextender id="caleTVLicIssueDate" runat="server" targetcontrolid="txtTVLicIssueDate"
popupbuttonid="ibnTVLicIssueDate" popupposition="BottomLeft" animated="true"
format="dd/MM/yyyy">
</cc2:calendarextender>
<asp:imagebutton id="ibnTVLicIssueDate" runat="server" imageurl="../images/img-calendar-day.png"
alternatetext="Calendar" tooltip="Pick Date" cssclass="date-picker" />
<asp:requiredfieldvalidator id="rfvTVLicIssueDate" CssClass="error" runat="server" controltovalidate="txtTVLicIssueDate"
display="Dynamic" errormessage="Required" setfocusonerror="true" validationgroup="TVLic"></asp:requiredfieldvalidator>
<asp:comparevalidator id="cmvTVLicIssueDate" CssClass="error" runat="server" errormessage="Not a valid date"
controltovalidate="txtTVLicIssueDate" operator="DataTypeCheck" type="Date" setfocusonerror="true"
validationgroup="TVLic" display="Dynamic" cultureinvariantvalues="true"></asp:comparevalidator>
<asp:customvalidator id="cuvTVLicIssueDate12Months" CssClass="error" runat="server" controltovalidate="txtTVLicIssueDate"
validationgroup="TVLic" display="Dynamic" onservervalidate="cuvDocIssueDate12Months_ServerValidate"
errormessage="Document must be less than 12 months old."></asp:customvalidator>
</div>
</asp:panel>
<asp:panel id="pnlTVLicApprove" runat="server">
<asp:LinkButton id="lbnTVLicApprove" runat="server" CssClass="screen-hide"
alternatetext="Confirm TV Licence" tooltip="Confirm TV Licence" Text="OK" CausesValidation="false" OnClick="lbnApproveConfirm_Click" />
<asp:imagebutton id="ibnTVLicApprove" runat="server" imageurl="../images/img-accept-doc-off.png"
alternatetext="Approve" tooltip="Approve" cssclass="approval-btn" causesvalidation="true" validationgroup="TVLic" OnMouseDown="HandleApproveClick('TVLic','lbnTVLicApprove');return false;" OnClientClick="HandleApproveClick('TVLic','lbnTVLicApprove');return false;" />
<span class="approval-label">Accept document:</span></asp:panel>
</div>
</asp:panel>
The app is written in c# but i havn't posted any actual code as all the user code related to this markup seems to work fine.
The problem is the CheckBox chkTVLic has causes validation set to false and autopostback set to true. So whatever happens when i check and uncheck the checkbox it should postback. Most of the time this is exactly what it does and the result is to show and hide pnlTVLic when it is checked and unchecked. However if any on the validators within the panel fire, the checkbox does not cause a postback the first time. It will on all subsequent times but never the first. However it should ALWAYS cause a postback. What could be stopping it. Before someone asks there is no use written client side code, everything is pure .net markup and c# code.
I don't see why it shouldn't postback when you check/uncheck the checkbox, but if the only purpose of that checkbox is to hide/unhide a panel, I would rather do it in javascript. Doing a full postback to the server just for hiding some panel seems really bad.
In javascript you can do this to hide the panel:
document.getElementById('<%=pnlTVLic.ClientID%>').display='none';
And this to show it:
document.getElementById('<%=pnlTVLic.ClientID%>').display='block';
It's going to be so much faster and better. Just put a regular checkbox instead of the ASP.NET one and subscribe to the onclick event.
Sorry, one more comment:
I think you are wrong when you say that the checkbox should ALWAYS cause a postback. No, if one of the validators fires inside the panel, the checkbox will not cause a postback until the condition is satisfied.
This is what I did and it worked.
on checkbox onclick event I disabled all the validation controls and immediately did Page_ClientValidate(); and it worked.

Show "passed" image or text after validating an asp.net (req. field)validator

I have the following asp.net code:
<asp:TextBox CssClass="mf" runat="server" ID="mail1" Width="270" />
<asp:RequiredFieldValidator ID="rfv1"
runat="server"
ControlToValidate="mail1"
Display="Dynamic" />
Now I want to show an image (or text) if the validation passes on the fly (no postback)
A jQuery solution is also fine by me, but that wouldn't be so safe if javascript is disabled.
Without relying on an external framework you can tap into the ASP.Net Client Side Validation framework to handle extended/advanced functionality. In this way you are working with the framework, augmenting it instead of replacing it.
A tiny bit of JavaScript is all that is needed to enable the behavior you want.
<asp:TextBox CssClass="mf" runat="server" ID="mail1" Width="270" OnChange="showValidationImage();" />
<asp:RequiredFieldValidator ID="rfv1"
runat="server"
ControlToValidate="mail1" ClientIDMode="Static"
Display="Dynamic" >
<img src="../Image/fail.jpg" />
</asp:RequiredFieldValidator>
<img id="imgPass" src="../Image/pass.jpg" style="visibility:hidden" />
<script language="javascript">
// This function will be called whenever the textbox changes
// and effectively hide or show the image based on the state of
// the client side validation.
function showValidationImage() {
if (typeof (Page_Validators) == "undefined") return;
// isvalid is a property that is part of the ASP.Net
// client side validation framework
imgPass.style.visibility = rfv1.isvalid ? "visible" : "hidden";
}
</script>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
Notice here that I am using a feature of ASP.Net 4 with ClientIDMode="Static" if you are not using .Net 4 then you will need to use the standard <%= rfv1.ClientID %> server side include to get at the client id inside your script.

Using FindControl: Accessing Controls in a Formview

I'm developing a simple Wedding List application, where guests can reserve the present they want to buy for the bride and groom. The Reserve page wraps a few fields inside a couple of panels, all wrapped inside a FormView.
The user enters their name, email and the quantity of items that they want to reserve, and the page will make the necessary reservations in the DB.
My first problem was that in FormView_ItemCommand, I couldn't reference any of the other controls in the FormView.... I figured this was a case for FindControl - but why do I need to for a Formview when I've never needed it for ListViews or DetailViews?
Secondly, I know the following code works..
Dim oCtrl as TextBox = Me.fvwReservation.FindControl("txtEmail")
Dim Test As String = oCtrl.Text
...but why can't I use...
Dim Test As String = Me.fvwReservation.FindControl("txtEmail").Text
??
Finally, I don't think I need it on this occasion, but I've been researching recursive FindControl variants, but I haven't actually found one that actually compiles! Any suggestions?
It's a lot for one post - thanks in advance.
Gratuitous Code Snippet:
<asp:FormView ID="fvwReservation" runat="Server" DataSourceID="dsGift">
<ItemTemplate>
<asp:Panel runat="server" ID="pnlDetails">
<h3>Reserve Item: <%#Eval("ShortDesc")%></h3>
<p>You have chosen to reserve the <em><%#Eval("LongDesc")%></em> gift.</p>
<p>Please enter your details below to confirm the reservation.</p>
</asp:Panel>
<asp:Panel runat="server" ID="pnlConfirm">
<div class="row">
<asp:Label runat="server" CssClass="label">Name:</asp:Label><asp:TextBox ID="txtName" MaxLength="50" runat="server" CssClass="Field" />
<asp:RequiredFieldValidator ID="rfvName" runat="server" ErrorMessage="You must specify your Name" ControlToValidate="txtName" />
</div>
<div class="row">
<asp:Label runat="server" CssClass="label">Email:</asp:Label><asp:TextBox ID="txtEmail" MaxLength="100" runat="server" CssClass="Field"/>
<asp:RequiredFieldValidator ID="rfvEmail" runat="server" ErrorMessage="You must specify your Email Address" ControlToValidate="txtEmail" />
<asp:RegularExpressionValidator ID="regexEmail" ValidationExpression="^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+#((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$" runat="server" ErrorMessage="Please enter a valid Email Address" ControlToValidate="txtEmail" />
</div>
<div class="row">
<asp:Label runat="server" CssClass="label">Quantity (max <%#Eval("QtyRemaining")%>):</asp:Label><asp:TextBox ID="iQty" MaxLength="2" runat="server" CssClass="Field" />
<asp:RangeValidator ID="rvQty" runat="server" ErrorMessage="The Quantity mmust be between 1 and 10" MinimumValue="1" MaximumValue="10" ControlToValidate="iQty" />
</div>
<div class="row">
<asp:Label runat="server" CssClass="label"> </asp:Label>
<asp:Button ID="btnReserve" Text="Confirm Reservation" CommandName="Reserve" runat="server" />
</div>
</asp:Panel>
</ItemTemplate>
</asp:FormView>
For your second question, FindControl returns a generic Control, and must be cast to the specific type of control in order to obtain access to the properties of that specific type of control.
You can do it in a one liner, like this:
Dim Test As String = CType(Me.fvwReservation.FindControl("txtEmail"), TextBox).Text
Regarding your first question, I would love to know the answer to that as well.
EDIT
Looked through a few other StackOverflow responses (specifically this one and this one). As the controls in the FormView template do not exist until the template is the active template, you cannot directly refer to them in the code behind. Thus, you must use FindControl during an appropriate event to access the controls.
Hmm, even in the FormView templates, I don't think that FindControl will work reliably, typically I would only use that with straight HTML rendered controls, not ASP.net generated ones.
I'm pretty sure that the templated controls should be available in the Server side code, (ie. txtEmail.text) if not, double check the template
A recursive FindControl is also pretty taxing on the Server and potentially unreliable.
You need to use recursive FindControl method in order to access the elements inside the FormView control. There are many implementations available and one of them is linked below:
http://www.highoncoding.com/Articles/606_Creating_a_BetterFindControl_and_MuchBetterFindControl.aspx

Resources