Extending ASP.NET validators - asp.net

I want to extend the asp.net validators such that I can make one validator dependent on another. The situation I have is that we have to validate a date in a textbox. Normally I would just use a combination of a RequiredFieldValidator (to ensure the date is provided), CompareValidator (to ensure the date is a date) and finally a RangeValidator (to ensure the date is within the required limit).
The problem with this is that the validators do not depend on each other, so as a result the user would see possibly all three messages at once for each validator when really all we want them to see is the most relevant message, i.e. if they entered "abc" in the date text box it would not be appropriate to show them the message saying the date was not in the valid range (even though technically I suppose this is true).
Currently to provide this kind of functionality we use a CustomValidator and just put all three validations within the server validate event handler and change the error message programmatically depending on what validation failed.
I would like to standardize this a bit more as it happens quite a bit in this application, I figure if I can make the validators dependent on each other this will solve the problem and also allow us to make use of the client side validation rather than having to do a postback especially to handle the custom validation.
The idea is that if one validator is dependent on another if that "master" is valid then the depended will perform its normal validation (EvaluateIsValid()) otherwise if the master validator is not valid then the other dependent validators will be valid.
I have come up with the following solution by inheriting from the various validator controls that already have been provided in the framework.
public class RequiredFieldDependentValidator : RequiredFieldValidator
{
[Description("The validation control to depend on for determining if validation should occur")]
public string ValidationControlToDependOn
{
get
{
object obj = ViewState["ValidationControlToDependOn"];
if (obj != null) return (string) obj;
return null;
}
set
{
Control control = FindControl(value);
if (control is IValidator)
ViewState["ValidationControlToDependOn"] = value;
else
throw new HttpException("ValidationControlToDependOn is not a validation control");
}
}
protected override bool EvaluateIsValid()
{
IValidator validationControlToDependOn = FindControl(ValidationControlToDependOn) as IValidator;
if(validationControlToDependOn != null)
{
return !validationControlToDependOn.IsValid || base.EvaluateIsValid();
}
return base.EvaluateIsValid();
}
Currently I have just coded it for the RequiredFieldValidator, ideally I would like to provide this functionality for all of the validators but I cannot see a way to do this without copying the above code into a similar class for each individual type of validator I want to provide this functionality for thus if there are any problems I'm going to have to go back and change this code on each validator type individually.
Is there a way I can "centralise" this code and have it easily used in the validators without having to write the entire validators from scratch just so I can change the class they inherit from further down the line.
Cheers,

You could override the Validate method in you page base. To add the validation dependency information in the page you can implement a not rendered control:
<my:ValidationDependency TargetControl="RegExp1" Dependency="Required1" />

You might want to look into a WebControlAdapter.
Basically allows you to override certain methods of webcontrols (conditionally for some browsers if need, but here can be for all).
In your case, you would want to override the EvaluateIsValid method and check if the control has any dependency on a 'parent' validator.
As an example, a TextBox adapter we recently created to render a 'maxlength' attribute to the control.
Public Class TextBoxAdapter
Inherits WebControlAdapter
Private ReadOnly Property TextBoxControl() As TextBox
Get
Return DirectCast(MyBase.Control, TextBox)
End Get
End Property
Protected Overrides Sub RenderBeginTag(ByVal writer As System.Web.UI.HtmlTextWriter)
If TextBoxControl.TextMode = TextBoxMode.MultiLine AndAlso TextBoxControl.MaxLength > 0 Then
writer.AddAttribute("maxlength", TextBoxControl.MaxLength.ToString)
End If
MyBase.RenderBeginTag(writer)
End Sub
End Class
To use it, just create a .browser file in your App_Browsers directory and setup the adapter there:
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.TextBox"
adapterType="TextBoxAdapter" />
</controlAdapters>
</browser>
</browsers>
The only complication that still remains in your case is how to store the dependent validator in order for the EvaluateIsValid to have access to this directory. You might consider a non-rendered control like Onof suggested or else Viewstate/Cookie/other storage mechanism.

you can have ValidationControlToDependOn property as of type List and add the validators into the list. So we can assume that the validator added later depends upon the validator added before it.
so your protected override bool EvaluateIsValid()
will change somewhat
foreach(IValidator validator in ValidationControlToDependOn)
{
return !validator.IsValid;
}

I'm looking into control extenders which seems like it could be promising but I cannot find many examples of doing anything but AJAX stuff with it.

Related

User Control, Shared Property, setting label text

I usually make user controls containing forms for adding and editing data for a particular table in my database. I then show or hide these controls as the user clicks "edit" buttons, etc. It's common practice (for me) to put properties in the code-behind, that are used for setting the ID of the item being edited, into a hidden label on the page, and of course leaving it blank for new items being inserted. I usually only use C#, however, this time around I have to use VB.NET.
So in C# I would do the following:
public static int EditID
{
get
{
return Convert.ToInt32(lblEditID.Text);
}
set
{
lblEditID.Text = value;
}
}
..and then when the user, say, clicks an "edit" link from a gridview, I would
//set the ID of the corresponding record, something like this:
MyUserControl.EditID = MyGridView.SelectedDataKey[0];
Cool. So now I need to do this in VB.NET, and here's my code:
Public Shared Property EditID As Integer
Get
Return Convert.ToInt32(lblEditID.Text)
End Get
Set(value As Integer)
lblEditID.Text = value
End Set
End Property
but I get a syntax error that says: "Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.", highlighting the lblEditID for both the getter and setter.
I can't find any other SO questions about this, and I have Google'd just about every permutation of keywords I can think of, so this must be something really stupid.
What am I doing wrong here?
EDIT: Yes I realize I could just use a Session variable instead of the label, but I would still like to know why this doesn't work and how I could make it work with a label.
You don't want a Shared property for this. lblEditID is a label that exists in an instance of a WebForm class:- it can't exist until an instance of this class has been created, hence the error.
I don't really understand how the C# worked as this should be the same but I'm not a C# expert.
If you remove the Shared keyword it will work as you want I believe

With ASP.NET viewstate, is there a best practice for when in the lifecycle to access the viewstate?

In building custom controls, I've seen two patterns for using the viewstate. One is to use properties to disguise the viewstate access as persistent data.
public bool AllowStuff
{
get
{
return (ViewState[constKeyAllowStuff] != null) ?
(bool)ViewState[constKeyAllowStuff] : false;
}
set { ViewState[constKeyAllowStuff] = value; }
}
The other is to use private member fields and to override the Load/SaveViewState methods on the control and handle it all explicitly:
protected override object SaveViewState()
{
object[] myViewState = new object[2];
myViewState[0] = base.SaveViewState();
myViewState[1] = _allowStuff;
return myViewState;
}
protected override void LoadViewState(object savedState)
{
object[] stateArray = (object[])savedState;
base.LoadViewState(stateArray[0]);
_allowStuff = (bool)stateArray[1];
}
(I cut out a lot of safety checking for clarity, so just ignore that.)
Is there are particular advantage to one method over the other? I can't see how they'd differ much performance wise. Version 1 is lazy, so I guess you save a bit if you don't need that particular value during a pass. Version 1 is also more abstract, hides the details better. Version 2 is clearer about when the data is actually valid and ok to read or modify (between the load and save) because it more clearly works within the ASP.NET lifecycle.
Version 2 does tend to require more boilerplate code though (a property, a backing private field, and viewstate handling in two places) as opposed to Version 1 which combines all that into one place.
Thoughts then?
The private member field approach is often used for objects who do not directly have access to the ViewState state bag. So in a sense, I'd use option one for custom controls, user controls, or pages, or anything that has a ViewState or similar property, but use the other option for an object that does not directly have access to ViewState (like a class you want to be able to "serialize" and store in viewstate). For instance, custom controls would use that approach to store state for child objects that do not directly reference viewstate.
HTH.
Fist of all I would use ControlState and not viewstate so it works correctly if in a container that has view state turned off.
Then i would override init, savecontrolstate, loadcontrolstate and databind.
and make sure to register that the control uses the control state i.e. Page.RegisterRequiresControlState(this)
oh and the advantage is that your control is more robust (user can't screw it up as easily) and will work when dynamically loaded and across postbacks "better"

How would you validate a checkbox in ASP.Net MVC 2?

Using MVC2, I have a simple ViewModel that contains a bool field that is rendered on the view as a checkbox. I would like to validate that the user checked the box. The [Required] attribute on my ViewModel doesn't seem to do the trick. I believe this is because the unchecked checkbox form field is not actually transmitted back during the POST, and therefore the validation doesn't run on it.
Is there a standard way to handle checkbox "required" validation in MVC2? or do I have to write a custom validator for it? I suspect the custom validator won't get executed either for the reason mentioned above. Am I stuck checking for it explicitly in my controller? That seems messy...
Any guidance would be appreciated.
Scott
EDIT FOR CLARITY: As pointed out in comments below, this is a "agree to our terms" type of checkbox, and therefore "not checked" is a valid answer, so I'm really looking for an "is checked" validation.
a custom validator is the way to go. I'll post my code which I used to validate that the user accepts the terms ...
public class BooleanRequiredToBeTrueAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
return value != null && (bool)value;
}
}
I usually use:
[RegularExpression("true")]
If you didn't want to create your own custom validator and still wanted to use existing attributes in the model you could use:
[Range(typeof(bool), "true", "true", ErrorMessage="You must accept the terms and conditions.")]
This ensures that the range of the boolean value is between true and true. However, whilst this method will work, I would still prefer to use a custom validator in this scenario. I just thought i'd mention this as an alternative option.
I too am looking for a way to have the model binder correctly handle check boxes with Boolean values. In the mean time I'm using this in the Actions:
Object.Property = !String.IsNullOrEmpty(Request.Form["NAME"]);
Maybe this will be of some use to you.

ASP.NET: Why is "_requestValueCollection" empty on PostBack?

Why is "_requestValueCollection" empty on PostBack?
I have a really strange problem with post backs. In some cases on post backs (this.Request.RequestType == "POST") have null "_requestValueCollection" member. And for ASP.NET that means this.IsPostBack == false.
So I have modified the Page_Load in the following way:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack && this.Request.RequestType != "POST")
{
//REGULAR INIT STUFF
}
else
{
//REGULAR SITE POSTBACK STUFF
}
}
What is possible danger of this approach? So far everything is doing OK (and is pretty rich and complicated page).
It isn't clear from your example what you are attempting to do with this code, so this is mostly a short in the dark.
You probably don't need the second part of the if statement. Checking IsPostBack alone should be sufficient.
_requestValueCollection is not a property, it is a field and probably isn't a good place to get at the data submitted by the client. I suggest instead that you consider using the Form property (this.Request.Form) or the Headers property (this.Request.Headers) depending on what you are looking for. Keep in mind that most of the time you can just get form values from the asp.net controls on the form directly.
You may also want to look at the Request.HttpMethod property if you need to determine the exact http method used to invoke the page.
Edit: Adding info about _requestValueCollection
The mechanics behind the _requestValueCollection being loaded are quite complex, but I took a look at the MS source and from what I can determine the page calls on every control on the page that implements the IPostBackDataHandler interface. For each of these it will call the LoadPostData method which adds the data for that control to the collection.
The main things that I can think of off the top of my head that might cause the collection to be null would be:
no server controls on the page implement IPostBackDataHandler
there is no server form, or the contents of the form weren't sent by the client
Alternately, the page may be using query strings to convey the data to the server, and the query string doesn't contain anything
As I said, this is a bit fuzzy. The Page class is very complex internally and so there could be other ways data gets put into that collection too, but this was all I could find on a casual examination.

View the data that LoadPostData event is loading in ASP.NET

What's the best way to view the data that LoadPostData event is loading to the controls in ASP.NET?
It's actually really simple. The NameValueCollection that get's passed to this method of EVERY control that implements the IPostbackDataHandler interface is the contents of Page.Request.Form. So you can access it at any time by getting a Watch on HttpContext.Current.Request.Form.
Ugh... I would suggest setting your IDE environment up to debug the .net framework, and set a breakpoint on the LoadPostData() method of Control. That's a bit heavy-handed, but if you're willing to wade through the recursive calls to the Control class (perhaps set a conditional breakpoint on the method?), you will be able to get to the data that way.
Good luck!
If you want to be sure you're looking at the data going into a particular control, you can subclass its control type and break during a custom implementation of IPostBackDataHandler.LoadPostData.
For example, you have a programmatically added control to collect the user's city. Change:
Public City As Textbox
to
Public City As BreakableLoadPostDataTextBox
Public Class BreakableLoadPostDataTextBox
Inherits TextBox
Protected Overrides Function LoadPostData( _
ByVal postDataKey As String, _
ByVal postCollection As System.Collections.Specialized.NameValueCollection) _
As Boolean
Return MyBase.LoadPostData(postDataKey, postCollection) ' Break here
End Function
End Class
Set a breakpoint on the Return call. When execution breaks, you should be able to see the postDataKey that's being used to read the control's new value out of the postCollection. You can of course augment this method to your heart's content with Trace calls and whatnot.

Resources