Validate - Web User Control - asp.net

I do not like to use the calendar from .NET, so I would like to have one Web User Control with 3 drop down boxes, day, month, year. [CODE DONE].
I want to be able to call this Control and initialize it with start year and end year, and with or without selected date.[CODE DONE].
This control will see if there is one valid date selected and return bool [CODE DONE].
Then in my web page I would like to able to see if that web user control is valid, in a way that I can use with the normal .NET validation (associate one required field), the problem is that I don't know where to put this code and retrieve it to the validation control on the web page. [CODE NOT DONE].
How can I do this?

There are two steps to integrating your custom server controls with the validation framework.
(1) Server side: you'll need to add a ValidationPropertyAttribute to your class, so the validation framwework knows what to look at when validating:
[ValidationProperty("SelectedDate")]
public class MyDateControl : WebControl
{
public DateTime? SelectedDate { get { ... } set { ... } }
}
(2) To hook up with client side validation, you have to make sure there's an input tag associated with your control. One way of doing that is rendering an <input type="hidden"> as the first child tag of your web control's HTML. The validation framework will pick up on that. The remaining thing to do here, is to set this hidden field through JavaScript each time your one drop downs changes.
This way, you can tie in with the existing validation controls. If you want different way to validate, you should look at a CustomValidator.

You want to use the CustomValidator control for this. See this tutorial that explains how to implement it with both a client-side and server-side version of the validation.

Related

How to change html view of web user control

I am creating a web user control for a simple poll. I am currently registering it on the page and then referencing it via tagprefix.
The form for the poll is in basic html (no server controls) and is in the front-end of the web control. How can I change the look of the user control depending on the settings passed into it? Is this possible without using server controls?
Update
Can I change the html layout of a user control? If so could someone post some examples. Please note I do not use asp.net form controls, so none of that please :)
You might be able to also use jQuery to replace existing css setting in your code. Create properties on for your user control, and then pass settings in the classes. Then use jQuery to replace them. This however requires jQuery to be linked to your page (or within your control) and you'd have to write the CSS classes out to the jQuery code (using server controls, but you could use the literal control so there's no excess code).
Personally I'd go with the option of using server controls instead of straight up HTML, you'd get alot more flexibility, and then passing through the settings would be pretty straightforward, put something like this in your controls backend code:
Private _TextBoxCssClass As String
Public Property TextBoxCssClass() As String
Get
Return _TextBoxCssClass
End Get
Set(ByVal value As String)
_TextBoxCssClass = value
txtBox1.CssClass = value
txtBox2.CssClass = value
End Set
End Property
You most likely want to have a property or event in the control that changes the css. It may end up best to add some server controls or javascript / jquery to make it easier.
If its only the styles you want to change, then you can expose a property to set the style attribuites of the respective control inside your User Control. If you want to control the whole HTML layout of the control then Custom Control is the viable option.

Custom TextBox Control with built-in client-side validation

I have a textbox in my application which has multiple validation on it e.g. RequiredFieldValidator, RegexValidation and CustomValidation. My page has several similar textboxes. So I just copy-paste and change id and controltovalidate properties and it is working.
Since similar tbxs are going to be used on another page as well, I think it would be nice to create my own custom TextBox control with built-in validation.
Here are two approaches I have found and tried:
1: Implement from IValidator perform my custom validation in Validate Method. As shown here: Self-Validating TextBox But it does not show how to implement client-side validation.
2: Create custom control that derives from TextBox and add asp.net built-in validators I need. As shown here:Custom TextBox. I tried the code and it works server/client side.
I like the first approach but don't know how to implement client-side validation. I know I need a client-side js function. I can do that. I know how to include my js file using Page.ClientScript class but don't know how to integrate all together and make it work.
I can create a UserControl or the second approach above but for now I am specifically looking to learn and implement client-side validation from custom control.
I am using Asp.Net 2.0. Thanks for any suggestions.
Well, you're right, you can always implement your custom server control that derives from TextBox and automatically associates a couple of validators. But usually you won't create custom controls as far as it is not explicitly needed and then through several different projects. For having client-side validaton you usually need JavaScript, but note that most of the ASP.net validation controls have their client-side validation already built-in (i.e. required field validators, range validators,...). Others (like the custom validator) allow to hook in your custom javascript.
An approach that sounds more reasonable to me is to have your TextBox controls as they are on your ASP.net page/usercontrol and to associate the validators from your code dynamically at runtime. Say in your OnInit event, you call a function RegisterRequiredValidators passing in a list of TextBoxes. I'm just thinking aloud:
public override void OnInit(...)
{
...
RegisterRequiredValidators(
txtFirstname,
txtSurname,
txtAge
}
...
}
public void RegisterRequiredValidators(params Control[] textBoxes)
{
//execute the logic of creating and attaching validators
}
That's just a stupid example, just to explain the context. In theory you can evolve this concept to register any kind of validators. We do something similar at work, by abstracting this in form of "rules" which ultimately are being rendered as ASP.net validators on the front-end.

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

Design time validation of custom ASP.NET server controls

I am creating a custom control which has some properties on it. The problem is that the control isn't valid without those properties being set and there aren't suitable default values for them.
How can I make sure that they are being set in the ASP.NET markup when being included on the page? Is there some kind of validation event that can be hooked into?
For example, the following control:
public class TestControl: Control
{
public string Source { get; set; }
}
At design/compile time there should be an error if the control is used without setting the Source property:
<Prototype:TestControl runat="server"></Prototype:JavaScriptInclude>
I know I could check this at runtime, but it would be nice to have some early checking going on as it could be overlooked if the validation is deferred until runtime.
Short answer: you cannot.
Controls should have default behavior if properties aren't set. Only way to facilitate this is by bypassing the adding of the control in the aspx page, and do all this in your codebehind where you'll have the default language constructs like constructors. But I assume you know that path :-)

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