I decided to use the ASP.NET Validator to validate my dozens of inputs of my WebForm. It works fine on the Client side. I mean, i'm totally ok with validating the inputs without "Posting the Page back" etc.
But when i try to use the Validator on code behind, it gives me that Page.Isvalid attribute, and i get confused with its reliability. Here is the questions that i couldn't answer by myself:
Is Validator reliable enough to be used on client side? (Besides disabling javascript, can it be manipulated?)
How does this Validator reach the validity information on server side? (Is there a generated C# Validator code somewhere or does it take the info directly from the client-side?)
Here is the code that i wrote to validate my inputs also on server side:
foreach (IValidator iValidator in Page.Validators)
{
if (!iValidator.IsValid) { return false; }
}
But, is it independent from .aspx and .js? Can i rely on it on server side?
You should always validate also on serverside, this is mostly done automatically by calling Page.Validate.
From MSDN:
This method is invoked when a user clicks any ASP.NET server control
that has the CausesValidation property set to true, which is the
default. These include the Button, ImageButton, and LinkButton Web
server controls, the HtmlInputButton, HtmlInputImage, and HtmlButton
HTML server controls, and controls that can automatically post back to
the server such as the TextBox, CheckBox, ListControl, and
BulletedList controls.
If you want to force validation of a different ValidationGroup you can call it manually:
Page.Validate("MyValidationGroup");
If(Page.IsValid)
{
// ...
}
Note that you should check Page.IsValid only after you have called the Page.Validate method, or set the CausesValidation property to true in the OnServerClick event handler for an ASP.NET server control that initiated the form processing.
Related
I have a webform application that uses asp.net validators. I have a bootstrap accordian (or any accordian jquery etc) and I only want to validate controls that are on the visible panel. I setup a validation group for each panel. I have a single submit button.
I was using jquery to set the validationgroup property, but it seems when done this way, the button ignores the value.
I have tried validating manually but the page seems to skip validation altogether in that case. I am really banging my head against the wall.
<asp:button ID="btnDeleteConfirmation" runat="server" Text="Save" OnClientClick="return Validate();" CausesValidation="False"/>
function Validate() {
var isValid = false;
isValid = Page_ClientValidate(mode);
return isValid;
}
the mode is set when the tab/panel is switched, the value is correct when I check it. The function is called and the return value looks good, but the page postbacks and then i get the following expected error:
Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate.
How do others handle validation client side when only one tab/panel needs to be validated and there is a single submit button?
Normally in this case I set the validation groups on each section properly, then on whatever button I need to do the validation I do
Page.Validate(groupName);
Then you can call Page.IsValid and it will only use the validated group. That way you don't have to do anything else. Don't associated a validation group for your button either.
I have an ASP.NET web form with validators that are disabled. I want to enable validators only AFTER Submit button is clicked and based on if the control is visible or not.
Here is my function:
protected void Submit_Click(object sender, System.EventArgs e)
{
if (ddlSite.Visible){
rfvSite.Enabled = true;
base.Validate();
} else {
rfvSite.Enabled = false;
}
The above code is working fine. But now I want to check if page is valid or not. If the page is Valid then I want to process the form. I don't know how to do this.
You have multiple options:
Try to split your controls into multiple validation groups, which will only validate the controls in a specific group upon submit.
Write your own custom validator. A custom validator can declare a client validation function and a server validation function. Creating a custom validator is well-documented.
As StevieB mentioned, if you hide the controls server-side, the validators won't be fired. If the decision to hide them is made on the client, that's more difficult.
Hook into the client-side validation functions and manipulate the validators. This can be difficult and may require changing internal ASP.Net scripts. Sometimes it's the only way to make web form validation do what you need it to. See this question for an example of extending/modifying validator behavior.
Since I'm new to asp.Net c#, I was wondering is someone can give me an
example or idea as how to achieve this?
Consider using ASP.Net MVC instead of web forms. The web forms model is old and "fights" you on tasks like this. If you are just starting out, I'd suggest at least investigating MVC and see if your time is better spent.
A lot of jquery plugins was created for this reason :
http://tinyurl.com/qetudk8
I believe if you add a
if(Page.IsValid) {
// Code here
}
around the button that is submitting the form, the page should fire off validation errors.
I am having some textboxes and dropdownlist controls but if i select the ddl value the validation errors are disappearing and after the button click they are reappearing but i want to show the errors even after a postback how can i do this??
Could you post your code so we can perhaps see what the specific issue might be? Without seeing any code, I would say try adding this into the Page_Load function:
if (IsPostBack)
Page.Validate();
Alternatively, add this to your DropDownList or whatever controls are initiating the postback:
CausesValidation="true"
.. as per the answer here: Validators do not Validate after postback occurs
Please remove your asp.net validators if added with the controls and also remove any client side validation in Java script. Now add validation code on the page you are redirecting to. If that validation fails redirect back to the controls page with proper messages to be shown
If you dont like the default behavior - don't use validation controls and implement them by yourself using client side programming.
How do I setup a default setting so that if I do not set an OnClick (i.e the asp.net OnClick attribute) explicitly for an asp:LinkButton tag, it will not render an onclick(html attribute for javascript) attribute client side? By default, asp.net adds an onclick='doPostBack....' for the LinkButton.
Case for use:
There is a LinkButton tag on the page. For this page, if the user has one friend, I only want to run client side code if the button is clicked and would not for any reason want to make a post back. If the user has more than one friend I would want a click to trigger a postback.
Solutions that include the following are not helpful:
Using any asp.net Ajaxtoolkit
Dynamically switching the control type (i.e. if friends == 1 use a asp:Hyperlink)
-I want to avoid this because it is not scalable. There might be many cases where I want an asp:Link tag to do a postback or to not do a postback depending on the user context or user attributes
Using OnClientClick (I am using jQuery would like to avoid this)
Solution that would be helpful if possible:
If I could see server side at runtime whether an OnClick event was explicitly set on an asp:LinkButton tag, this would solve my problem, too. any ideas?
How about rather than dynamically switching the controls (as you mentioned is a solution you don't want), you could always use an asp:HyperLink and set the NavigateUrl property to redirect your page back to itself with a query string of some sort indicating what was clicked.
If you don't want the post to happen at all, simply leave the NavigateUrl property blank.
Of course, this will be pretty worthless if the rest of the page is dependent on ViewState and such.
http://forums.asp.net/t/1129106.aspx
This link explains how to see server side at runtime whether an OnClick event was explicitly set using reflection
I have 10 defined textboxes with strings.
I have to check all if they are not empty while clicking ok button
whats the cleanest way to check them all and when function is at end. each checkbox which was empty to give this a specific CSSclass. perhaps. ClassError. ( which highlights red)
I'm happy for answers.
I would add RequiredFieldValidators to them, as well as a ValidationSummary control.
edit: You can also add fancy AJAX effects with the ValidatorCallout from the AJAX toolkit.
edit: Validator controls also support client-side validation.
Using javascript or C#?
Javascript I will create an array of textbox and loop through it.
C# just go FindControl within a Panel or the Container of the text box and go something like this
foreach(Control C in ContainerID.Controls)
{
if ( C is TextBox )
{
if ( String.IsNullOrEmpty((C as TextBox).Text))
{
// Do things this way
}
}
}
Something like this would work on the client side using jquery:
$('input').filter(function(){return this.value=="";}).css("CSSclass");
edit: I just saw the C# tag, I'll leave this here for posterity though.
What you're doing might be simple enough to do easily with some custom javascript code, though I would say that in general the built in validator controls are both easier to use and more robust than a simple validation routine that someone might write. In addition to client-side validation, the validator controls also perform server-side validation to ensure that the data submitted is truly valid, in case someone has javascript disabled in their browser.
If validator controls are included on the page, then they will include some javascript functions that you can invoke, such as Page_ClientValidate(). I believe this will return a boolean telling you whether validation passed and will trigger the visual indicators that identify what the errors are. You can execute Page_ClientValidate('') to trigger only a group of validator controls; actually I think you must do that in order to trigger validation on any validator controls that have a value in their ValidationGroup property, as I don't think Page_ClientValidate() will trigger their validation logic.
There is a CustomValidator control that you can point to your own client-side function if you want, in case you do have some special validation logic that you can only implement through a custom javascript function. This is nice to use, because then your custom javascript function will be executed by the built-in validator framework along with any other built-in validator controls that you might choose to include on the page.
Side note regarding client-side validation: I suggest that you avoid doing the following to trigger validation:
onclick="return myValidationFunction();"
because if there is any other javascript code being injected into the onclick event, your return statement will prevent it from executing. So instead, I suggest doing this:
onclick="if(!myValidationFunction()) return false;"
That's bitten me enough times that I thought I'd just throw that out there. This problem is particularly noticeable if you have an ASP.Net button on which you've set the UseSubmitBehavior property to false, as it will cause the button to render as an HTML "button" control instead of a "submit" control, and as a result, executing a return statement, either true or false, will prevent the button from triggering a postback.