debug a CompareValidator (ASP.NET) - asp.net

What is the best way to debug a CompareValidator that always fails the validation? Is there any way to see what the values are that it's comparing to maybe get a clue as to what's going wrong?

Use Firebug to debug the javascript that .Net inserts

If you are not familiar with the other debugging methods, easiest way for you may be utilizing the Response.Write calls to print the values in your button event to see if they are equal to each other:
Response.Write(TextBox1.Text.ToString().Trim());
Response.Write(TextBox2.Text.ToString().Trim());
Response.End();
Update
For simplicity, I will use CompareValidator to check a data type.
You probably have something similar to the following in your ASPX (client side) code:
<asp:TextBox ID="txtTest" runat="server" />
<asp:CompareValidator ID="cvTest" runat="server"
ControlToValidate="txtTest"
Operator="DataTypeCheck" Type="Date"
Display="Dynamic" ErrorMessage="Incorrect format!" />
<asp:Button ID="btnTest" Text="Test Compare Validator"
onclick="btnTest_Click" runat="server" />
In your codebehind (server side), put the following in your btnTest_Click event to see the value that is entered in txtTest:
Response.Write(txtTest.Text.ToString().Trim());
Response.End();
But keep in mind that there more robust debugging utilities that VS offers. This is just a quick-and-dirty way for your purpose.

Related

ASP.NET Regular Expression Validator VS Required Field Validator OR both?

I don't really know if I should be using both the Regular Expression Validator and Required Field Validator or what? I have just a normal form in ASP.Net (Visual Studio). I want to make sure the user types in the correct characters, such as for a phone number (which is why I want the reg ex control), but I also want the field to be required. So should these be combined or what is the best way to do this?
Right now I just have the required part working, like this:
<asp:RequiredFieldValidator runat="server" id="RequiredFieldValidator2"
controltovalidate="TextBoxLocation" errormessage="Required"
/>
You can use both of them, but make sure to add Display="Dynamic" on both of the controls.
<asp:RequiredFieldValidator runat="server" id="RequiredFieldValidator1"
controltovalidate="TextBoxLocation" Display="Dynamic" errormessage="Required"
/>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Enter valid Phone number" ControlToValidate="TextBoxLocation" Display="Dynamic" ValidationExpression="^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$" ></asp:RegularExpressionValidator>
Both, simply because one validates client side and the other is server side.
This allows you to make sure the user didn't alter your clientside JavaScript and then send bad data.

RequiredFieldValidator have to click twice

I have run into the same problem as described here.
Only the question is marked as answered with only an explanation as to why you may have to click twice when using a RequiredFieldValidator on input fields - once as the blur of a textbox(for example) will correct the validation and then again to actually post the form.
I don't want to have to click a button twice! Does anyone know a solution or workaround to this?
You could add EnableClientScript=false to the validator.
That prevents the client-side validation, so you will always get a postback (which may not exactly be what you want, though). The validation will still be done, just server-side.
Be sure to wrap the button-click logic in a if (Page.IsValid) { ... }, to check the status of the validators.
Apologies for not posting code previously I assumed this to be a standard problem with the RequiredFieldValidator, but have since realised my particular problem was coming from a CompareValidator, used to ensure entered passwords matched.
The CompareValidator was causing the issue that I described, causing me to have to click away from the field to blur and validate, before being able to click on the post button.
I'm not sure why but changing the Display of the CompareValidator from Dynamic to Static has cleared the problem up.
If the validator is Display="Dynamic", and the appearance of the error message causes the submit button to move, then the MouseUp event is not received by the submit button. In this case, the validation fires and clears the error message, but the submit button does not fire. To solve the problem, either set the the validators to be Display="Static", or rearrange the form so that the submit button does not move when error messages appear.
Here's a way to reserve about one, vertical line of space for a dynamic validation message:
<div style="height:1.5em;overflow:visible;">
<asp:RequiredFieldValidator ID="R1" runat="server"
ErrorMessage="Name is required" ControlToValidate="TextBoxName"
Display="Dynamic"></asp:RequiredFieldValidator>
</div>
I did not find it necessary to set EnableClientScript="false", although that did help for a CustomValidator that had no client-side validation function implemented.
Posting your code is always a good idea, That way we could run your code in a test environment and modify it to ensure it works before posting our answer.
I would suggest adding
causesValidation="true"
to your button to see if that works.
I have a better idea.
Add Text="" to textbox Control.
Add InitialValue="" to Validator Control.
What it will do, when it will be posting, it will find the value of the text box is still the initail value and it will throw an error and the form will not be posted.
Try this:
<asp:RequiredFieldValidator ID="reqFieldCloseComment" ControlToValidate="tbCloseComment" ValidationGroup="ChangeStatus" ErrorMessage="Please enter a reason" Display="Dynamic" runat="server" InitialValue=""></asp:RequiredFieldValidator>
<asp:TextBox ID="tbCloseComment" runat="server" CausesValidation="true" TextMode="MultiLine" Height="107px" Width="400px" Text=""></asp:TextBox>
<asp:Button ID="btnCloseRequestFinal" Text="Finish" CssClass="CloseReqButton" runat="server" ValidationGroup="ChangeStatus" />
Here is code that is working fine for me and helping to get rid of double click.
<asp:TextBox ID="TextBox1" runat="server" autocomplete="off"
Enabled="true" MaxLength="20" onfocus="SetActiveControl(this);" Text=""
CausesValidation="true" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="TextBox1" Display="Static" ErrorMessage="Ha!" SetFocusOnError="True" EnableClientScript="true" ForeColor="" InitialValue="" />
$(function() {
$("input.btn").on("click",function(){
if(Page_BlockSubmit == true) {Page_BlockSubmit = false};
})
});
Page_BlockSubmit is a JS variable defined by the js generated from code behind when you define the validator . I haven't went deeper to know why MS need this variable, but the scenario is:
the first click will make Page_BlockSubmit become false.
the second click will check the value of Page_BlockSubmit and return true.
if you implemented the code I posted, every time you click the button, the variable will be set as false which will trigger the submit at every click.
And, you can use google chrome to trace the value of Page_BlockSubmit.

Validation summary control not showing message?

I have a page with TextBox to enter a Mobile Number.
For that I have validated it using RequiredFieldValidator and RegularExpressionValidator
with display=none:
And also I have placed a ValidationSummary Control
<asp:ValidationSummary ValidationGroup="mobile" ShowSummary="false" ID="vsValid"
runat="server" ShowMessageBox="true" Enabled="true"
DisplayMode="SingleParagraph" />
<asp:TextBox ID="txtMobileNumber" runat="server" CssClass="Qinputbox"></asp:TextBox>
<asp:RequiredFieldValidator Display="None" ControlToValidate="txtMobileNumber"
ID="reqValidMobileNo" runat="server" ErrorMessage="*"
ValidationGroup="mobile"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ControlToValidate="txtMobileNumber" Display="None"
ID="regExValidMobileNo" runat="server"
ErrorMessage="Please enter a valid mobile number."
ValidationExpression="^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9]
(\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$"
ValidationGroup="mobile"></asp:RegularExpressionValidator>
when I entered characters in the TextBox it is not showing the summary.
What might be the problem?
From you code fragment:
ShowSummary="false" Looks like a problem.
You should set either ShowSummary="false" to true or EnableClientScript="true". I'm assuming that you want the latter because you have ShowMessageBox="true".
Have a look: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.validationsummary.enableclientscript%28v=vs.71%29.aspx
Use this property to specify whether
the ValidationSummary control updates
itself using client-side script. When
set to true, client-side script is
rendered on the client to update the
ValidationSummary control, if the
browser supports that feature. When
set to false, no client-side script is
rendered on the client and the
ValidationSummary control only updates
itself on round-trips to the server.
In this situation, the ShowMessageBox
property has no effect.
In web.config setting:
<httpRuntime targetFramework="4.5"/>
This setting turns off Javascript injection of validation (client side).
Remove this and retry.
Ensure that you do NOT have this in the web.config file:
<xhtmlConformance mode="Legacy"/>

Setting a server control property from the content page

I need to validate a textbox to ensure the submit date is older than Today. I wanted to use a CompareValidator to do that, but unfortunately the following code doesn't work:
<asp:CompareValidator ID="cvtbDateExpiration" ControlToValidate="tbDateExpiration"
Operator="GreaterThan" Type="Date" ValueToCompare="<%= DateTime.Today %>"
ErrorMessage="Card has expired" runat="server" />
The compiler tells me that ValueToCompare="<%= DateTime.Today %>" is wrong: "This is not scriptlet. Will be output as plain text."
Is there a simple way to achieve this (without setting it using the Code Behind)?
Thanks!
It's generally set as follows:
ValueToCompare='<%# DateTime.Today.ToString("MM/dd/yyyy") %>'
... and you have to call DataBind() on the control (directly or indirectly).

Custom validation not working with delete buttons?

In a ListView, I have a CustomValidator set up to validate a field whenever a button with CommandName="Delete" is clicked.
<ItemTemplate>
<asp:TextBox ID="NameTextBox" Text=<%# Eval("Name") %> runat="server" />
<asp:Button ID="DeleteButton" Text="Delete" CommandName="Delete" ValidationGroup="Delete" runat="server" />
<asp:CustomValidator ValidationGroup="Delete" SetFocusOnError="true" Display="Dynamic" OnServerValidate="CustomValidator_ServerValidate" runat="server">You can't delete this.</asp:CustomValidator>
</ItemTemplate>
However, the error message is never displayed and the processing continues. What's strange is that the custom validation method is called, finds the field, and properly sets up e.IsValid to false. It does not matter whether I check Page.IsValid or not, because the error message is not displayed anyway.
It works if I remove the CommandName="Delete" from the button.
With Google I found the following solution, which seems to indicate someone has had a similar issue:
http://devio.wordpress.com/2007/12/11/formview-delete-button-and-customvalidators/
But I want to make sure that this solution is the way to go. I mean, is custom validation really not supposed to work with a delete button in a databound control, seriously?
I've alrealy heard about a problem like that, he solved it by doing it entirely differently. Like, instead of the customValidator, he puts a Label set EnableViewState="False" and Visible="False" and he check on the delete event the conditions and put the response back into the label. Maybe it can't works for you too?
But, if you realy ask "Why?????", I know he didn't find the exact reason ...

Resources