Custom TextBox Control with built-in client-side validation - asp.net

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.

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 required field validation

Hi
I need to validate two fields in an Asp.net form, where the requirements is like any one of them is required. For example, there is Page title and sub-heading input boxes, so any one of them is required. Can I do it using the validation controls Asp.Net provides?
Any kind of help is greatly appreciated. Thanks in advance.
You can use a CustomValidator control (MSDN) in ASP.NET for special situations that are not supported by any one of the other standard validators. It was created for this reason.
Microsoft describes how to create a custom validation function here.
Here's another tutorial on implementing it.
Or if you google for keywords like "creating a custom validator in asp.net" you can pick and choose from various solutions for your own project.
For your case, as an alternative to using a CustomValidator, you could explicitly change whether your required field validators are enabled by using the ValidatorEnable() JavaScript function.
// disable validation control
ValidatorEnable(RequiredFieldValidator1, false);
You can then write custom logic in JavaScript to determine the case in which each validation control is either enabled or disabled, and tie it to one of the (client-side) events of the text boxes (onblur, onchange, onkeyup, etc).
Then, on the server side you can write similar logic to do the same thing by setting the "Enabled" property and put this logic in your button click event before you check the IsValid state.
If all you are doing is conditionally determining when something is required, changing the enabled state is your best bet. Exactly what can be done is documented in ASP.NET Validation In Depth.

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.

Best way to start building a custom-rendered control?

I am needing to create a custom control.
Basically, I'm wishing to create a light weight(and better using jquery) Accordion control.
What are some good references for getting started with doing such a thing. I will be deriving it from a Panel because it's very similar(just needs a bit of JS tacked onto the end) but I want it to only be able to add controls of a certain type. I'm having trouble finding any information about custom rendered controls.
Can anyone point me to some references? Also, for the ID tag in HTML, would you use UniqueID or ClientID?
Any good ASP.NET book should have a chapter devoted to custom controls. If all you wanted to do was add some JS to Panel I would think you could just do this:
public class AccordianPanel : System.Web.UI.WebControls.Panel
{
protected override void OnPreRender(EventArgs e)
{
base.Render(writer);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "accordianscript", ScriptText);
}
}
Or create a User Control with nothing but a Panel and the javascript in the ascx. Limiting the allowed controls is problematic at best...
As for the ID, always use ClientID to reference controls in client-side script.
I would consider using the AjaxControlToolkit, and look at the documentation there (on asp.net) for how to use that to create a custom control or extender. That makes it easy to create custom controls, and you can embed JQuery in those components. The ACT provides all the plumbing; there is less work for you to use the MS ajax framework and link everything together.
I've used it and it works well, though I must admit I've recently scrapped it for my set of AJAX components within my custom framework (http://www.codeplex.com/nucleo). That was for other reasons.
I missed part of your question; to validate for allowing only certain controls, you can override the AddedControl method, which is called when the control gets added. You can validate control types in this method.
Or, most controls implement a custom control collection, and I believe there is a CreateControlCollection that you can use to create a custom control. This custom control collection validates the control within the Add/AddAt method.

Validate - Web User Control

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.

Resources