CustomValidator ServerValidate method does not fire - c#

I've put a CustomValidator on my form. I have not set its ControlToValidate property. In its ServerValidate event I've written the following:
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
args.IsValid = false;
}
I put a breakpoint to this method but it seems to never come to that point. But if I do this on another form it works like a charm.
The ValidationGroup property of both the button and the CustomValidator are the same
I tried deleting this property in both the button and the CustomValidator, still does not work.
It seems as there's something formwide. I just put a CustomValidator on the form and do not touch any of its properties other than just setting its ServerValidate event method.
EDIT: Here's the aspx part:
<asp:CustomValidator ID="CustomValidator2" runat="server"
ErrorMessage="This is a test"
onservervalidate="CustomValidator1_ServerValidate"
ValidationGroup="PA"></asp:CustomValidator>
<asp:Button ID="btnPensionersOK" runat="server" Text="OK" Width="75px"
onclick="Button1_Click" ValidationGroup="PA" />

Try to force the validation in the button-click handler via Page.Validate:
protected void Button1_Click(Object sender, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
// servervalidate should have been called
}
}
Edit(from comments):
If you want the customvalidator to validate if nothing was entered/selected in your controls, you need to set ValidateEmptyText to true. You also might want to let the CustomValidator replace the RequiredFieldValidators.
I assume that the validator-order on the aspx decides whether or not a customvalidator's severvalidate is called if a previous Validator already has made Page.IsValid=false. Or ASP.NET is so smart that it assumes the SeverValidate to be costlier than a simple text-is-empty check.

I would also like to put some more help for those who will use CustomValidators and RequiredFieldValidators at the same time. One should take into account that Client side validation takes place first. And the server side validation will occur only after PostBack. I'm sure you got it but just in case this is not quite clear: It means first all the controls that are bound to certain client side working validators must be valid to let Postback to occur. After Page. IsValid is True server side stuff takes place and posts back any changes which includes server side validation messages.
So here are the ways one can make both CustomVCalidators and other built in validators to work at the same time.:
Set both groups of validators to work on Client side. In this case we must ensure that for the custom valitor(s) we spacify the script that will make validation on the client side. Without writing script and just filling in the ServerValidate method the validation will take place in the server.Even if EnableClientScript property is set to True.
Set both groups of validators to work on server side. To do so simply set EnableClientScript to False. But note that this will load the server.

Related

ASP.NET custom validator is not working

I've done everything this page told me to do, but it's not working, i've seen people posting about this problem and being told to add a required field validator, i've done that, still not working.
Here's the client side part
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ControlToValidate="TextBoxUsername"
ErrorMessage="Username already exists"
OnServerValidate="CustomValidator1_ServerValidate"
ValidateEmptyText="True" <!--tried without this line-->
ValidationGroup="form"> <!--tried without this line-->
</asp:CustomValidator>
Here's the C# server side code
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){
args.IsValid = false;
}
looks pretty simple, right ? it should keep appearing all the time, right ?
well, it only appears at the beginning and then disappears forever and that's because I have this line in the page_load() method, but i also have it in the button_click() method.
Page.Validate();
First up, remove the validation group, and add in Text:
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ControlToValidate="TextBoxUsername"
ErrorMessage="Username already exists"
Text="Username already exists"
OnServerValidate="CustomValidator1_ServerValidate"
ValidateEmptyText="True">
</asp:CustomValidator>
ErrorMessage will show in a ValidationSummary control and Text should show where the validator is.
Update the button to cause validation (I believe true is the default anyway, but lets be explicit):
Then check if the page is valid after click, Page.Validate doesn't need to be called as it will be automatically for things that CauseValidation.
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// Do Cool Stuff
}
}
Additionally, drop a breakpoint on the click method when checking it as you don't have any client side wiring (e.g. ClientValidationFunction="somejsfunction" on the validator) so you will only hit this code when you get through to server side validation.

ASP.Net Server Side Custom Validator control help needed

I have a page with a textbox control, a Custom Validator, a button to save entered data and code to handle the custom validation.
I set up a simple code test just to see how the Custom Validators work.
I hope to add more validations that check multiple controls later. The same thing happens if I do add the ControlToValidate attribute for the textbox control.
(I don't think I need a "ControlToValidate" attribute for this. I plan to validate multiple controls later. I can't put all the controls I am validating in that attribute.)
When I run my app, the save takes place and the validation is happeing - the message appears. I don't understand why the save isn't stopped when I enter "3" in the textbox I am checking. If the validation is happening, and if the IsValid = false, why is the save taking place?
Here is the Custom Validator:
<asp:CustomValidator ID="VisitSaveCustomValidator" runat="server" OnServerValidate="VisitSaveCustomValidator_ServerValidate" ValidationGroup="SaveVisit_val"></asp:CustomValidator>
Here is the button:
<asp:Button ID="SaveVisit_btn" runat="server" Visible="false" Text="- Save Visit -" ValidationGroup="SaveVisit_val" OnClick="SaveVisit_btn_Click" />
Here is the code for the Custom Validator:
protected void VisitSaveCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
if (VisitNumber_tbx.Text == "3")
{
args.IsValid = false;
VisitSaveCustomValidator.ErrorMessage = "The Visit Number cannot be 3.";
}
else
{
args.IsValid = true;
}
Please let me know if I need to add more code or more information.
I thought this would be pretty straight-forward. I followed an example in a book and some online. I understand that the page is going back to the server to be validated. But, shouldn't the save be stopped since the IsValid = false?
It seems like the save is happening first, then the validation code executes, which causes the message to appear.
Thanks.
I believe you may have to manually call the validate method.
VisitSaveCustomValidator.Validate();
Then check to see if it was valid.
VisitSaveCustomValidator.IsValid();
This can be put in the button click event.

Get the validationgroup that is used on a postback

I'm working with a legacy project in C# (.NET 2.0). In this project there are two validationgroups. One for custom login control and one for users to submit to a newsletter. The problem I ran into is that when a user submits to subscribe to a newsletter some custom code is triggered in the page_prerender() method which only should be triggered when a user tries to login.
I have been looking for a solution to recognize which of the two groups is used on postback so I can ignore the custom code when needed. My idea was to try and check which of the two validation groups is being used to validate. Unfortunately after spending a fruitless few hours on google I've not been able to find anything to let me know how to actually known which validationgroup is used when validating. Is there any way to find out?
<asp:Button ID="btn_newsletter"
runat="server"
Text="Verzend"
ValidationGroup="newsLetter"
meta:resourcekey="bnt_newsletter"
OnClick="handleNewsLetter"
CssClass="roundedButtonBig"
/>
<asp:Button ID="LoginButton"
runat="server"
CommandName="Login"
Text="Inloggen"
ValidationGroup="lgnUser"
meta:resourcekey="LoginButtonResource1"
CssClass="roundedButtonBig"
/>
The following code should only trigger when the LoginButton is pressed and it needs to be done on Pre_render(). Or alternatively pass the correct ValidationGroup (where now null is passed).
protected void Page_PreRender(object sender, EventArgs e)
{
//Register custom ValdiationErrorService added errors to JavaScript so they can be added into the popup.
ValidationErrorService.RegisterServerValidationMessageScript(Page, null);
}
to check which validation group is valid, call:
Page.Validate(“newLetter”);
then check
Page.IsValid;
this will return the value. Scott Gu has more on his blog
edit you are also wanting to know which button was clicked within the prerender event it sounds like as well. While you can't find that out from the parameters passed into the page prerender, you can rely on the button events occuring prior to the page_prerender event. within the aspx pages code behind, create a member variable. this variable will be used to denote if the prerender logic should be executed.
next, within the click events of the two buttons, set that local variable to denote if that button should fire the logic you want in the page_prerender event.
last, check your local variable within the page_prerender method, and encapsulate your logic within an if statement based upon your new member variable.
Happy Trails!

Is there a quick way to clear a customvalidator as soon as the fields been changed?

I have a custom validator that uses server side validation.
I also have a bunch of client side required field validators and these clear as soon as something is entered in them.
I was wondering is there some sort of attribute that clears the custom validator as soon as I edit the field?
That should work ..
1- Write a client side validation status reset function:
function CustomValidator_ClientValidation(sender, args) {
args.IsValid= true;
}
2- Set the ClientValidationFunction of your CustomValidator to that function:
<asp:CustomValidator ID="CustomValidator" runat="server" EnableClientScript="true"
ClientValidationFunction="CustomValidator_ClientValidation" .... >
3- Remember to assign the name of your field to the ControlToValidate property..

Attach RequiredValidator on custom server control rendering a TextBox

I don't know whether this is really possible, but I'm trying my best.
If I have a (complex) custom server control which (beside other controls) renders a TextBox on the UI. When placing the server control on a page, would it be possible to attach a RequiredField validator to that server control, such that the validator validates the Text property of that control which points to the Text property of the rendered TextBox?
Of course I could incorporate the RequiredField validator directly into the server control, but this is for other reasons not possible (we are rendering RequiredField validators automatically on the UI).
Thanks for your help.
I think one solution is to put your TextBox control inside a Panel then you add the RequiredValidator control dynamically on the Page_Load event handler.
<asp:Panel ID="Panel1" runat="server">
<MyCustomTextBox ID="TextBox1" runat="server"></MyCustomTextBox>
</asp:Panel>
<asp:Button ID="Button1" runat="server" Text="Button" />
then
protected void Page_Load(object sender, EventArgs e)
{
var validator = new RequiredFieldValidator();
validator.ControlToValidate = "TextBox1";
validator.ErrorMessage = "This field is required!";
Panel1.Controls.Add(validator);
}
I put the CustomTextBox inside the panel to assure that the validation controle place is correct when added
I got it, the 2nd time that I'm answering to my own post :) Next time I'll do a deeper research before.
For those of you that may encounter the same problem. You have to specify the ValidationProperty attribute on your server control's class. For instance if your server control exposes a property "Text" which is displayed to the user and which should also be validated, you add the following:
[ValidationProperty("Text")]
Then it should work.

Categories