Using ASP.NET validators to validate Composite Control data - asp.net

Background: I have a toolset of CompositeControls that I use to build forms. The controls themselves tie in to some jquery validation for basic validation tasks.
Problem: I want to make the validation of these CompositeControls more flexible by allowing developers to use the ASP.NET validators (i.e. RegExValidator, RequiredFieldValidator, CustomValidator, etc) to validate the data in one of my CompositeControls.
Example: I'd like the developers to be able to do something like this:
<asp:ValidationSummary runat=server HeaderText="There were errors on the page:" />
<custom:TextBox id='SomeTextBox' Label='Enter Name Here:' text='' runat='server' />
<asp:RequiredFieldValidator runat=server ControlToValidate=SomeTextBox ErrorMessage="Name is required."> *
</asp:RequiredFieldValidator>
I have added the "ValidationProperty" to the composite textbox, but the RequiredFieldValidator (or any ofthe other validators) don't seem to recognize the textbox or the data coming from it. The textbox (and all other custom CompositeControls I built) inherit CompositeControl, have the attribute "ValidationProperty" set to the public property that exposes the data element of the control, and contain a "string ValidationGroup" property as well.
Question: Does anybody know what else or what specifically a Composite Control requires to play nice with the ASP.NET validators (I'd prefer avoiding including instances of all the validator types in the composite control, unless of course that is necessary)?

I last looked into this in about 2005, but from what I remember, there are two separate issues here:
How the client-side validation code finds the value to validate
How the server-side validation finds the value to validate
Setting ValidationProperty is only going to affect the server-side validation, if I'm not mistaken. If you haven't already, check whether the IsValid property of the validators is set to false on the server side after you post back.
This may have changed, but I think it was also true that validation controls could only validate controls that had the same naming container as they did.
On the client side, I'm a little hazier, but I think the situation is still that the validation script will look for an element with the client ID corresponding to the server ID it was told to look for, and look for a value property on that. If you're not exposing one on the client side, it's not going to be able to find anything to validate.
If you have time, it'll help a lot to step through the validation javascript. That'll teach you a LOT about how client-side validation finds the values that it validates.
Hope this helps.

Related

How to trigger ASP.NET client-side validations without submit?

I have a website in ASP.NET (WebForms, NOT MVC) which has a survey form divided in several slides. Each slide has a next button that, obviously does a transition (client-side, not post back or remote request) to the next slide.
In each slide I have several ASP.NET controls with their related validators. I want this validators to be triggered when I click the next button (or maybe when each input loses focus?).
I remembered ASP.NET doing client side validation on lost focus, but maybe I'm wrong... (I quit doing ASP.NET development about 3 years now, so I can't remember)
Thanks
UPDATE:
It would be better to make ASP.NET trigger each validator when the associated control lost focus. I remember ASP.NET doing this (or am I dreaming? =P)
First you need to make sure all of your validators have target controls specified using the "TargetControlID" Attribute on the validators.
Then you can set up a validation group per page and specify the group name in your next button and on the controls themselves.
If you are using regular expression validators you can choose them from this website
To Validate Client Side
If you are using custom validators you can create a client function and specify it on the custom validator using the ClientValidationFunction attribute and by setting EnableclientScript = "true" on the custom validator.
Just be sure your client function has sender and args parameters.
It looks like there's a supplied JavaScript function called Page_ClientValidate which should be callable to check the validation manually from JavaScript. I haven't used it, though, so YMMV.
put all your client-side validators into the same validationgroup and with your 'next' button add the same validation group. When you click the button it will automatically trigger all the validators before it does the post-back.
as to manually triggering the validation...
you might also be able to use ValidatorOnSubmit(). I remember doing this in another project but i'm having a hard time finding the code.
It seems that enabling 'SetFocusOnError' on each validator triggers the validation whenever I try to leave the field.
In short decorate your model, now Data Annotations are supported from Asp.Net 4.5
Check my Answer here..Client side webform validations

ASP.NET: How to get same validators control to be both client-side and server-side

For the ASP.NET validator controls, I want to use both client-side validation for the user experience and server-side validation to guard against hackers. ASP.NET documentation leads me to believe that if EnableClientScript="True" then there will be no server-side validation if client-side validation is possible for the user agent. To get server-side validation, the documentation says use EnableClientScript="False", which bypasses client-side validation altogether.
Am I misunderstanding how the validator controls work? I ask because it seems obvious that many developers would want both client and server side validation together, and I find it hard to believe both together is not possible with one of the standard validation controls.
If I am understanding the ASP.NET documentation correctly, then I can find only two options:
Use two validator controls exactly the same except for their ID and EnableClientScript properties. Obviously ugly for maintaining two controls almost the same.
Write some code behind to check if postback then invoke the Validate method on the validator group. Why write code behind if there a way to be automatic from the control?
Is there a way to do so using a single validator control with no code behind?
Thanks in advance for your input.
The server-side validation will always occur, so you don't have to worry about it. The only way around that would be to use the CustomValidator or create your own validator class from BaseValidator that don't do anything server-side.
By default, server-side validation occurs after Page_Load() and before any triggered events (e.g. button click). In your Page_Load(), however, you can force a Page.Validate(). After validation has occurred you can check the Page.IsValid property.
I recommend you read ASP.NET Validation in Depth. Also, it's not what you asked for, but it is fundamental that you understand the page lifecycle and ViewState (if you're not using MVC). Almost everything you will encounter makes use of it.
You are misunderstanding how the validators work. You always get server validation, bit client validation is optional. The only exception to this is the custom validator where you do not have to do anything server side if you don't want to.
use an asp validator in your markup, then on postback do the following:
Page.Validate()
if(Page.isValid)
{
// Validation passed
}
According to this Microsoft source, "the Web Forms page framework always performs validation on the server, even if the validation has already been performed on the client."
There is a lot more information there about how to implement the validation controls in ASP.Net 2.0. Presumably, the basic behavior has not changed in subsequent ASP.Net releases.

Allowing any property/attribute on a server/usercontrol

I've noticed that on most, if not all, standard web controls in the System.Web.UI.WebControls namespace, you can add any properties you want to them without crashing the page.
Take the asp:Button control for an example.
This code is perfectly valid:
<form runat="server">
<asp:Button runat="server" Text="Test button" crapAttribute="crapValue" />
</form>
Now, I've got a custom server control which crashes if I add arbitrary attributes to it. It only accepts attributes which have a corresponding public property defined.
The error I get is something like this "The control does not have a public property named "crapAttribute" ".
I would like my custom controls to accept any attribute without crashing. What do I need to do for that to work?
I've looked at the standard controls in Reflector and they do have all kinds of attributes and stuff but there was nothing that I saw which immediately caught my eye.
My custom controls are inheriting from WebControl for what it's worth.
You don't have to do anything in particular to allow arbitary attributes to be added the control markup. Things deriving from WebControl would normally scoop up these attributes and dump them in the Attributes collection.
I can't think of reason why this would fail. You would have to remember to render the Attributes collection in your implementation of Render if you have one.
Can you add a simple example of the code of a new control that fails to your question?
One way of doing it is adding the custom property in code behind
myCustomControl.Attributes.Add("customproperty", "value");
This should do the job for you.
However, I am interested in knowing how to do it in the server control itself.

Is is possible to get ASP.NET input controls to act like a basic HTML Form?

ASP.NET has a number of nice features regarding making data input pages:
Adding input controls is easy (<asp:...).
The system automatically generates member variable for the controls.
Post-backs automatically populate the members variable with the returned values.
and some not so nice bits
post-backs seem to be tied to JavaScript for even the simplest of cases. For instance, with statically defined pages, using only basic controls, that are known at compile time.
My questions:
Is is possible to get the first list without the second?
What features does that JavaScript give the user?
What does that JavaScript actually do?
What is the technical reasons that it's used even in trivial cases?
As it happens my assumption were in error: See here
It really depends on the types of controls you are trying to use here -- the only ones that implement javascript are those that can't natively cause a postback (ie, an input/submit button are the only two that can). If you are using a LinkButton, ImageButton, or anything that you set "AutoPostBack = true" on will turn javascript on in order to cause a postback.
Other controls can also potentially use javascript if they are more advanced such as the Calendar. The technical reason for using javascript here is to provide automated postback when the controls require more advanced server interaction -- think about it, a link is meant to only ever be a link and if we're trying to make it operate as a button we have to force it to do just that through javascript interaction.
So that being said, yes you can definitely use ASP.NET without it having javascript you just have to avoid the controls that implement it by including functionality you couldn't possibly have without it. You can just as easily add HTML controls and add the runat="server" attribute and gain member variables to the control from code-behind.
Here's what came to my mind:
What features does that JavaScript give the user?
Client side validation.
What does that JavaScript actually do?
For exmaple, it ensures that the correct (server-side) event handlers are called, by setting the __EVENTTARGET hidden field.
Is is possible to get the first list without the second?
You can use normal HTML controls instead of the ASP.NET controls. Then on the server-side, you can read the control's values from the Form collection.
I assume you mean the javascript associated with an <asp:Button /> control, right?
In addition to the reasons mentioned by Fooberichu, the javascript can also help with ASP.NETs client side validation framework.
But I think it's primary use is to alert the framework what events it should fire on the postback in the page behind.
So if you had two buttons on the form, SaveButton and DeleteButton, the javascript helps the framework know whether it should execute the SaveButton_Click event or DeleteButton_Click event.
Hope this helps.

Web User Controls and Validation

I have an ASP.Net web user control that contains a TextBox and a calendar from the Ajax Control Toolkit.
When I include this user control on my page I would like it to participate in input validation (there is a required filed validator set on the TextBox inside the UC), ie. when the page is validated the content of the UC should also be validated. So I had my UC implement the IValidator interface, which worked well except that I could not set the validation group on the user control. Apparently I'm supposed to inherit from BaseValidator to do that, but I can't since I'm already inheriting UserControl.
There's got to be a way to deal with this common scenario.
You can reference a control within a user control by seperating the two with a dollar sign:
<asp:RequiredFieldValidator ControlToValidate="MyUserControl$ControlId" runat="server" />
Create a property on your new user control that sets the validation group on the contained validator. Then from your markup, all you need to do is just set the ValidationGroup property on the control, and that'll roll to the validators contained in the user control. You likely don't need the interface or inheriting from BaseValidator unless you are creating JUST a validation user control.
public string ValidationGroup
{
get
{
return MyRequiredFieldValidator.ValidationGroup;
}
set
{
MyRequiredFieldValidator.ValidationGroup = value;
}
}
Try adding [ValidationProperty("NameOfPropertyToBeValidated") on your user control class.
If you are planning to add lots of validation in the future it may pay off to check out Peter Blum's DES (Data Entry Suite) - it has numerous enhanced controls for data entry and validation including conditional validation scenarios and the one you are describing. Licensing is very reasonable compared to the time required to develop it yourself.

Resources