ASP.Net Server Side Custom Validator control help needed - c#

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.

Related

Using $(this).val() returns Invalid Postback error

I have an ASP.NET C# web form that uses jquery to validate user input before that input is handled by the server. When I say "validate", I mean that I check to ensure my user has given input in certain required fields before anything else happens. This check is wired to the "OnClientClick" event of an ASP.NET button control. If the client script finds missing input, it returns false. Otherwise, the button's OnClick event fires.
<asp:Button ID="submitBtn"
OnClientClick="if (!addBtnClick(event)) { return false; }"
UseSubmitBehavior="false"
runat="server" Text="Submit" OnClick="submitBtn_Click" />
The inputs to be checked consist of textboxes and drop down lists, both of which are coded in the page as server controls, and marked as required by a class value. I check the value of these inputs one at a time using the "each" function, and get the value of the input being checked with "$(this).val()".
$(cls).each(function () {
var val = $(this).val();
// do other stuff
});
My problem is that this is somehow causing an "Invalid postback or callback argument" error, and I know it's "$(this).val()" that's the culprit because if I comment out only that, passing in some generic value to my variable for example, my application runs fine.
I've tried registering my jquery code with RegisterClientScript, but that doesn't change anything. Has anyone seen this before?
EDIT: "$(this).val()" continues to throw this error even if the server-side isn't involved. I'm using this code to reset my form as well, clearing all input fields. After posting this it occurred to me that some of my textboxes have event listeners attached, so maybe this is where the error is coming from?
Turns out, no. Even with my event listeners commented out, I still get the error on the client side. I can use "$('input').val('')" with no problem, but this clears all the input fields and I need to be able to ignore certain ones.

CustomValidator ServerValidate method does not fire

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.

Why won't my form post back after validation?

I have an asp.net page with multiple validation summaries setup with ShowMessageBox="True" and several validators. I have run into a situation where when validation fails the validation summary displays correctly but then the next click that would normally trigger a postback of the page does not trigger a postback. So the steps look like this:
Click button that triggers validation.
Validation fails and a messagebox with the failure message is displayed.
Click a different button which does not validate but should trigger a postback nothing happens
Click same button as step 3 again postback happens as expected.
What could cause this behavior?
EDIT: The validation was being done in the following manner. In the asp page:
<asp:Button runat="server" id="btn" onClientClick="return DoValidation();" />
In the javascript:
function DoValidation() {
if (!Page_ClientValidate('group1'))
return false;
if (!Page_ClientValidate('group2'))
return false;
return true;
}
After working on this and making careful use of the debugger I finally found out that when you do validation the way described in the edit to the question a boolean is set on failure that blocks the next PostBack of the page from going through. I believe this is done when validation is being done automatically instead of explicitly as I'm doing here. Changing the javascript described above to look like this:
function DoValidation() {
if (!Page_ClientValidate('group1')) {
Page_BlockSubmit = false;
return false;
}
if (!Page_ClientValidate('group2')) {
Page_BlockSubmit = false;
return false;
}
return true;
}
Causes the problem to go away. Hopefully this will help the next person who makes the same mistake I did.

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!

Conditional validation

I have an ASP.NET web app (with C#). In it I have a form with several fields and validators. For one of the validators I only need to validate when:
a certain textbox is empty
and a certain record does not exist in the database (this is already handled).
I know I can't enable/disable the validator on page_load because something might be entered into that textbox. I also tried the following in the onclick event of the submit button but it didn't seem to work:
Validator1.Enabled = true;
Validator1.Validate();
I also tried Page.Validate() but that didn't work either...
Can anyone please help?
Thanks
Use a customvalidator. Inside the Validation Event you have code like this pseudo code:
OnValidating(object sender, ServerValidateEventArgs e)
{
if(CertainTextBox.Text.IsNullOrEmpty() && CertainRecordDoesNotExistInDB))
{
// validate
// and set e.Valid to the desired validation output
}
else
{
e.IsValid = false;
}
}
this things should be done by JavaScript on client. Then on submit you should validate at server side.

Categories