Creating custom ASP.NET validator - asp.net

I have created a custom control and a custom validator (extending BaseValidator). On custom control I have set ValidationProperty("Values"). The problem is that validation doesn't work when postback is sent unless I execute Page.Validate(). And when I call Page.Validate() all validators are executed which is not what I would expect on postback.
How do I create custom validator which would be executed when control value changes and validates just that control?

That is not how validators work. Unless you are using a ValidationGroup setting, all the validators on your page will automatically fire. You do NOT have to explicitly call Page.Validate(). You DO need to wrap your code in a check like this, however:
if(Page.IsValid)
{
//do something here
}
Unlike client-side validators, the server-side validation does NOT prevent the page from posting back and processing events as normal.
To create a control which only validates when the control value changes would require a bit of hackery, since the change event fires after the validators have been executed.

Have you tried using validation groups?

Related

I'm having trouble understanding page validation

Okay, so I have my asp.net page with all of my comparison and requiredfield validators. This leaves me with two concerns.
What additional validation do I need? Do I need anything in the code behind? I want them to be unable to hit the 'save' button until their textbox information is complete, and it seems to be doing this with just the validator controls, but I'm unsure if there are other steps I need to take.
If I have a requiredfield validator and I want to turn it off under special circumstances, where in the codebehind would I set it to true? Can I do it on the 'save' button click, before it prevents the button from functioning?
1.
You need as many validations as necessary, you can create many different validators.
You need server-side validation in the code behind. If a postback occurred then the form passed the validation, but there are some validation features which are unusable at client-side. For instance you register to a homepage and you have a form where the username is required and there is a regular expression validator too. These validators will run at client-side. But if the username has to be unique and you can only check that using a database then obviously this can't be checked at the client-side, therefore, the client-side will evaluate the page to be valid, a postback will occur and it's the job of the server-side to check whether the username is unique.
Note that you can create custom validators if you need to do anything exotic.
2.
Depending on your needs you can set the Enabled property of your validators whenever you need to do that. Read more about that here.
As per my knowledge,
We should include a check for "Page.IsValid" on the server side (code behind) whenever we are using the ASP.NET Validators. This would ensure a check at the server side even if the javascript is being disabled on the browser.
No, you can't do that on the save button click as the button click would not be hit until the validation passes.
Hope this Helps!!
1 if you want add validation server
protected void Button1_Click(object sender, EventArgs e) {
//Proceed only if the validation is successfull
if (!Page.IsValid) {
return;}
}
2 You can set CausesValidation="false" to button
The #1 question with Page.IsValid is ok.
The requiredfieldvalidator is a javascript validator, so you can't disable it from codebehind once it was enabled (unless it satisfies the condition and you can go through). But it's possible to disable it via javascript, check this code:
ValidatorEnable(workPhoneValidator, false);
Link: Dynamically enable or disable RequiredFieldValidator based on value of DropDownList

Custom validator only fired on first button click?

I have a custom validator and some other validators on the page. But whenever I click the submit button for first time it only fires the custom validator and when I click the button for second time it's validating rest of the validators. Please let me know if you have any solution.
Thanks
Check your Page_Load to make sure you are not hiding or enabling something after the second call. I had a similar problem before and it confused the heck out of me until I realized I was manipulating a Panel in the Page_Load that contained the validator.
Other than that, you would need to post code (your Page_Load and Click event).
On Client Side when
OnClientClick="return SomeCustomClientCode();"
Is called, asp.net validators e.g required field validators are disabled and it does not gets listed in validators collection and does not validate the field validated by this validator and page post backs if custom validation passes.
To avoid this explicitly enable asp.net validators in Custom validation code or else where so that it gets activated before page postback or in the begiining of custom validation as follows:
ValidatorEnable(document.getElementById('<%=rfvDDLStatus.ClientID%>'), true);
rfvDDLStatus ==> required field validator which was not firing.. ValidatorEnable ==> Client API to enable asp.net validator

ASP.Net validation controls behaviour

Asp.net validation controls generates client-side javascript that validates controls.
I decided to have a look into the ASP.NET validation JavaScript and I can see there is a function that hooks into the onchange events for controls to make sure the validation script runs when a values is changed.
My question:
Is there a way to disable this onchange validation? I want the validation to be done on the submit and then show the necessary error messages.
Thanks
Simply set:
EnableClientScript="False"
On the control.

purpose for <pages enableEventValidation="false">

I've used the following in web.config
<pages enableEventValidation="false">
This corrects a problem we've been having with Ajax.
We have a web page that if you browse to directly using a standard HTML hyperlink works fine.
If you browse to the page from another page via link inside a gridview and response.redirecting in the RowCommand event to the page passing an ID in the querystring. The page throws errors from controls inside the panel stating
"Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. "
I'm happy to leave the page validation as false as it seems to have had no other effect.
Any ideas what's happening?
Read the documentation.
EDIT: For security reasons, it's probably best to leave it set to true wherever you can.
I would therefore recommend that you set it to false only on the individual AJAX pages where it causes problems, while leaving it true in web.config.
From here
Invalid PostBack or CallBack argument error is basically raise because of Event Validation feature. The EventValidation feature is a new feature in ASP.NET 2.0, and provides an additional level of checks to verify that a postback from a control on the client is really from that control and not from someone malicious using something like a cross-site script injection to try and manipulate things. It is part of our overall strategy of increasingly adding security in depth levels to the programming model -- so that developers can be secure by default even if they forget to add security checks of their own.
Now, Invalid PostBack or CallBack argument error may occur when you are firing click event and the object is rebinding or its properties are changed in Page_Load event or someone is trying to hack into your system with cross site scripting. Each time .Net Framework render a page then it associate a unique Guid for all the controls. When binding a gridview or repeater, on each databind framework will associate a new guid for the contorl. So every time when you are firing event make sure Page_Load event does not change the control, because if the control changed the it will have a different Guid which have acutally fired the event for postback. Here are some scenario with this error.
1) Invalid Postback or Callback argument in GridView Problem may be: You are binding data in Page_Load event with either Object Data Source or Manual Binding with function call. This will make your GridView bind data on every event fire of any control. When you are firing any GridView command with OnRowCommand, before RowCommand fire your GridView will rebind and all control within it will be assigned to new id. So RowCommand could not get the item which have fired the event. Solution for Invalid Postback or Callback argument in GridView: You can bind your data within this if condition
if (!IsPostBack)
{
//Your code for Bind data
}
This code will definitely give you solution if this not work then check whether any other control is not giving error.
There is one thing worth adding here: If you want to disable the event validation for a specific control, rather than the entire page, there is a workaround documented here and here (and now referenced in the relevant Connect suggestion):
Simply subclass the relevant WebControl class, and don't set the SupportsEventValidation attribute on the subclass. The subclass will be exempt from event validation.

ASP.NET - how to stop unrequired server validation

I have used ValidatorEnable to disable a RequiredFieldValidator in javascript. However on postback the control being validated by the validator is still validated ... even though I disabled the validator on the client.
I understand why this is happening since I've only disabled the client validation ... however is there a nice way to determine that I've disabled the client validation and to then disable the server validation on postback?
You could, when you disable the client validation (presumably with JavasScript?), also set up values in a hidden input that you could query in page load method. This way you can examine the value of the hidden input (via the Request.Form{] array) to disable the validators on the server side prior to the validation event firing.
Another option would be to override the pages Validate() method to disable the validators based on the same rules that hid them on the client side.
It's not clear from your question, what you are disabling. The RequiredFieldValidator has an both an Enabled and an EnableClientScript property.
If you want to disable validation on both client and server you should set Enabled to false.
To disable just client side, set EnableClientScript to false.
Peanut, I just encounted the same issue you are. On the client-side I have javascript that disables required field validators depending on their selections in the UI. However, the server side validation was still firing.
During load, I added a method to disable my validators using the same rules I have on the javascript. In my case, it depended on the user's selection of a radio button:
this.requiredValidator.Enabled = this.myRadioButton.Checked;
This seems to work on the SECOND page load, but not the first. After debugging, I discovered that the wrong radio button is considered to be checked when this line was firing. The View State/Post Data wasn't applied to the control at the point when I was checking it to disable my validator. The reason I placed this during load was to make sure I disabled the validator before it fired.
So, the solution seems to be to have something like the line above AFTER ViewState, but BEFORE validators.
Overloading the Validate() method, as palehorse suggested, worked and allowed me to ensure the server side validators were enabled/disabled based on the current selections of the user.

Resources