What do you suspect when ASP.NET ignores a CustomValidator? - asp.net

This is as much a code maintenance issue as a code issue, but I have a WebForm that no longer checks it CustomValidator. It worked when I last touched the code over a year ago, but it no longer works now that the user has requested some changes ...
The WebForm contains a data-bound drop down with a default " - All -" item with String.Empty as its value. When the user clicks the submit button, the validator should check that the drop down's value is not String.Empty. I've set break points in the client validation code and the server validation code, but neither fire.
Where would you start looking? What are the usual suspects? I have, of course, compared my working copy to what is in source control, but nothing jumps out as being suspicious.
Just in case it matters, here is my code:
<asp:DropDownList ID="_AssessmentDropDown" runat="server" DataSourceID="_AssessmentsData" CausesValidation="true" AutoPostBack="false"
DataTextField="AssessmentName" DataValueField="AssessmentName" OnDataBound="_HandleAssessmentsBound">
</asp:DropDownList>
<asp:CustomValidator ID="_AssessmentValidator" runat="server" ClientValidationFunction="_HandleValidateAssessment_Client"
ControlToValidate="_AssessmentDropDown" ErrorMessage="* You must select an Assessment."
OnServerValidate="_HandleValidateAssessment" />
<asp:ObjectDataSource ID="_AssessmentsData" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetData"
TypeName="DataTableAdapters.GET_GRADE_ASSESSMENTSTableAdapter">
<SelectParameters>
<asp:ControlParameter Name="GRADECODE" ControlID="_GradeCodeDropDown" PropertyName="SelectedValue" />
</SelectParameters>
</asp:ObjectDataSource>

I notice a couple of issues
I don't think you need a CausesValidation=true if AutoPostBack is set to false
You do not use validation groups, so that cannot be the cause
Why not use a RequiredFieldValidator?
If you want to fire validation on empty fields, set the ValidateEmptyText property to true

A CustomValidator doesn't fire if the control it is validating has an empty value, so a CustomValidator should always be accompanied by RequiredFieldValidator

Some troubleshooting steps:
Is this the only validator on the form?
Is validation enabled on the page?
Is validation enabled for the targeted control?
Is the validator itself enabled?

I would take a serious look at the ValidationGroup.
If something has been left out of the group, it wouldn't validate anymore. Otherwise, make sure that you don't have any javascript error (for the client side) and that the method that is "OnServerValidate" has a break point inside.

Is the validator in the same validator group as the submit button?

Related

asp:RequiredFieldValidator makes postback with empty fields

I've faced the following problem with my aps validator. I have a textbox with asp validator. When the user leaves the textbox empty and click on the submit button the validation message shows, but the page does a postback. Any ideas what may cause this happen?
Heres the validator:
<asp:RequiredFieldValidator ID="valReqName" runat="server"
ControlToValidate="txtName" Display="Dynamic" ErrorMessage="blq blq">
</asp:RequiredFieldValidator>
<asp:TextBox ID="txtName" style="font-family:Tahoma, Geneva, sans-serif;
color: #4F4F4F;" runat="server">
</asp:TextBox>
Many thanks,
Anton
EDIT
I have two tabs in an UpdatePanel. The validation problem is part of the second tab, where the user makes some inputs. When I've remove this trigger:
<asp:AsyncPostBackTrigger ControlID="lnkUpload" EventName="Click" />
The postback problem was solved, but another problem occurred. Well at least the postback is removed. Thanks for all answers.
(lnkUpload is the id of the second tab linkbutton)
EDIT 2
Well here is the solution. It appears that my problem was the same like in this article. http://jeffreypaarhuis.com/2011/08/08/validation-not-working-in-updatepanel/
I'm posting the solution as it might be useful for someone else.
"This is the problem:
When a validator is loaded on the page it creates a bit of javascript to support the clientside validation. When you place a validator inside an usercontrol that isn´t visible by default, and this usercontrol is in an updatepanel, it does not create that javascript properly.
This is the solution:
Outside the updatepanel, I did above, create a dummy validator with a dummy textbox using a dummy validationgroup like so:"
<%--dummy validator to make ajax validation possible--%>
<asp:RequiredFieldValidator runat="server" CssClass="hidden" ControlToValidate="dummyTextBox" ValidationGroup="dummy"></asp:RequiredFieldValidator>
<asp:TextBox runat="server" ID="dummyTextBox" CssClass="hidden"></asp:TextBox>
It appears that my problem was the same like in this article.
Have you tried the solution in this thread:
ASP.net RequiredFieldValidator not preventing postback
Remove the following line from web.config
<xhtmlConformance mode="Legacy"/>
"If I remove the line, my validation works the way I expected it to. Googling that uncovered a bunch of blog posts about how VisualStudio adds that line to the web.config when upgrading web apps from .net 1.1 to .net 3.5.
The blog posts were mainly complaining about how that field interferes with .net's AJAX stuff, but I'm guessing it messes with the JavaScript emitted for the RequiredFieldValidator in a similar fashion."
Please add ValidationGroup to your validator(valReqName) and button.
Add this attribute to your validator.
EnableClientScript="True"

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.

Is it possible to apply a particular CSS to a textbox in case it cannot pass a RequiredFieldValidator?

Is it possible in ASP.NET to enforce a Requiredfieldvalidator control to add a CssClass to a TextBox in case it fails the validation?
<asp:TextBox ID="txtSomeInput" runat="server" />
<asp:RequiredFieldValidator runat="server" Text="*" ErrorMessage="This is required." ControlToValidate="txtSomeInput"
<!-- Do something so that if validation fails, add CssClass 'failed' to txtSomeInput; possible? -->
/>
You can achieve that using CustomValidator with code-behind validation logic using CssClass property.
Or inherit RequiredFieldValidator and extend validation failure reaction
A possible solution would be to use this example.
It relies on altering and using some of the javascript code generated by asp validation controls and has the advantage of being usable with all kinds of validation controls and does not require a post back (if client validation fails no postback is made to alter the class of the text box).
best of luck,

Server side validation

I am having an issue with the requiredfieldvalidator control not working on an ASP.net page. I have completed the attributes of that field properly, but when I test it, the postback is allowed to happen even if the field in question is blank.
So I want to do server side validation instead. What is the best way to do that? In the event that caused the postback? Also, if I find out the field is blank, how do I get the user back to the screen with all other values they placed on other fields intact and a message saying "This field cannot be blank".
EDIT:
This is the code:
<asp:TextBox ID="fName" TabIndex="1" runat="server" Width="221px" CausesValidation="True"></asp:TextBox>
<asp:RequiredFieldValidator ID="FNameRequiredFieldValidator" runat="server" ControlToValidate="fName" InitialValue="" ErrorMessage="Filter Name cannot be blank." ToolTip="Filter Name cannot be blank.">*</asp:RequiredFieldValidator>
You need to provide the markup for your Button / Link control as well.
The 'CausesValidation' attribute is not supposed to be used on TextBox controls.
The button you click needs to have that attribute set to "True".
Please provide that markup and then I can advise on the alternate server side validation.
To enable Client-side Validation, set the EnableClientScript="true" on the RequiredFieldValidator.
You should also always validate on the server side too. But the RequiredFieldValidator doesn't let you do any special-handling server-side. Just check if Page.IsValid(). This will return false if the field is not supplied.
If you want to do custom validation, use a CustomValidator.

Automatically rebind controls on ASP.NET postback

Is there a flag or property value I can set to have my controls re-bind on every page load, instead of just the initial one? I'm still very new to ASP.NET, so I would like to do it properly (if such a way exists) before resorting to the first thing that "works".
I am working on a simple WebForms page, which boils down to a few SQLDataSource-bound Repeaters; for example:
<asp:Repeater ID="ExampleRepeater" runat="server" DataSourceID="ExampleDataSource"
OnItemDataBound="ExampleRepeater_ItemDataBound">
<ItemTemplate>
<asp:Label ID="DataboundControlID" runat="server" Text='<%# Eval("ExampleColumnName")%>' />
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="ExampleDataSource" runat="server" ConnectionString="example_connection_string"
SelectCommand="ExampleStoredProcedure" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="exampleValue" Name="parameter1" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
After the user has interacted with my page, they can initiate a postback which will change the state of the database. I'd like the postback'ed page to reflect the changes to the database. Please let me know if I can clarify my situation any further.
After your processing i.e. updating database you can re-bind the Repeater by calling DataBind method like:
ExampleRepeater.DataBind();
In my experience, some controls do, others don't. E.g. the standard ASP.NET controls from Microsoft always worked for me automatically, whereas the ASPxGridView from DevExpress needs a manual rebind on every postback/callback.

Resources