Site-wide CustomValidator methods. - c#

I have a web form that uses CustomValidators, and I have a few validation routines in my "validators.js" file that I can set as the ClientValidationFunction on each CustomValidator. Routines such as ValidateRequired, ValidateEmail, ValidateUsername etc.
I would like to define a set of globally available CustomValidator functions within my c# code itself, however I'm failing to grasp how to do this.
The ideal solution would be something along these lines:
Validators.cs:
protected void ValidateUsername(object sender, ServerValidateEventArgs e){
// Validation Logic here
}
Default.aspx
<asp:TextBox runat="server" id="txtUsername">
<asp:CustomValidator runat="server" OnServerValidate="ValidateUsername" id="cvldUsername" ControlToValidate="txtUsername" ClientValidationFunction="ValidateUsername"></asp:CustomValidator>
I know I could probably add the event into my default.aspx.cs which then calls my Validation function for a bool response and then return a true/false on IsValid -- But I was wondering if there was a more elegant way to do this.
I feel I may be missing something.
Thanks in advance,
Dave

Related

Can I create a custom attribute that runs a codebehind method?

I added an onkeyup attribute on Page_Load for a TextBox. I have it so that it is able to run a JavaScript function fine. I was wondering if I can change it to run a method in the code-behind file. I tried this.methodname, but it asks for a string as a parameter.
The TextBox in question:
<asp:TextBox ID="txtCurrBlk" runat="server" onkeyup="txtUpdate()"
style="width:80px" Text='<%#Eval("currentBlack") %>'
AutoPostBack="true" />
Under page_load in this C# file:
txtCurrBlkTotal.Attributes.Add("onKeyUp", "CallScript(this)");
The function I want to run in the same code behind file:
protected void keypressUpdateTotals()
{
readingTextChanged();
updateTotals();
}
So the onkeyup will currently run whatever JavaScript function I set it to, but I need it to run a method inside the code-behind instead.
The TextBox control only has the server-side TextChanged event, and you cannot easily make a "custom" server-side event. However, you can let your JavaScript CallScript() function make a post-back to the server by calling the _postback() function.
Add the OnTextChanged attribute to your TextBox control (I recommend removing the AutoPostBack attribute too, but that's up to you):
<asp:TextBox ID="txtCurrBlkTotal" runat="server"
onkeyup="CallScript(this)"
OnTextChanged="txtCurrBlk_TextChanged" />
I've added the onkeyup directly here, but you can use txtCurrBlkTotal.Attributes.Add("onKeyUp", "CallScript(this)");, if you want.
Now, at the end of the CallScript() function, call the _postback() function for your TextBox control:
function CallScript(sender) {
//...
__doPostBack("<%= txtCurrBlkTotal.ClientID %>", "");
}
This will post-back to the server every time the onKeyUp event is fired. You can capture and process that in the TextChanged event:
protected void txtCurrBlkTotal_TextChanged(object sender, EventArgs e) {
keypressUpdateTotals();
}
Alternatively, you can make your JavaScript CallScript() function make an Ajax call to your code-behind keypressUpdateTotals() function. I think that's a better solution, but you can decide for yourself.

ASP.NET custom validator is not working

I've done everything this page told me to do, but it's not working, i've seen people posting about this problem and being told to add a required field validator, i've done that, still not working.
Here's the client side part
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ControlToValidate="TextBoxUsername"
ErrorMessage="Username already exists"
OnServerValidate="CustomValidator1_ServerValidate"
ValidateEmptyText="True" <!--tried without this line-->
ValidationGroup="form"> <!--tried without this line-->
</asp:CustomValidator>
Here's the C# server side code
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){
args.IsValid = false;
}
looks pretty simple, right ? it should keep appearing all the time, right ?
well, it only appears at the beginning and then disappears forever and that's because I have this line in the page_load() method, but i also have it in the button_click() method.
Page.Validate();
First up, remove the validation group, and add in Text:
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ControlToValidate="TextBoxUsername"
ErrorMessage="Username already exists"
Text="Username already exists"
OnServerValidate="CustomValidator1_ServerValidate"
ValidateEmptyText="True">
</asp:CustomValidator>
ErrorMessage will show in a ValidationSummary control and Text should show where the validator is.
Update the button to cause validation (I believe true is the default anyway, but lets be explicit):
Then check if the page is valid after click, Page.Validate doesn't need to be called as it will be automatically for things that CauseValidation.
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// Do Cool Stuff
}
}
Additionally, drop a breakpoint on the click method when checking it as you don't have any client side wiring (e.g. ClientValidationFunction="somejsfunction" on the validator) so you will only hit this code when you get through to server side validation.

Validator controls must always have Display="Dynamic"

i've been working on this for some time now but I can't seem to be able to find the answer... Google doesn't really help me today!
I'm working on an C# website that uses a lot of forms with a lot of validation on it. Big forms which have to be typed by hand, (no problems there though).
The problem that I have is that I always want my ValidationControls to have the Display Property set to dynamic.
I have found a work around but I'm not convinced that this is the best solution.
Currently I have a BaseValidatorControlAdapter that sets the validators display type to "Dynamic" like this:
public class BaseValidatorControlAdapter : ControlAdapter
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
System.Web.UI.WebControls.BaseValidator _control = (System.Web.UI.WebControls.BaseValidator)this.Control;
_control.Display = System.Web.UI.WebControls.ValidatorDisplay.Dynamic;
base.Render(writer);
}
}
This is then triggerd by adding an App_Browser which looks like this
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.BaseValidator"
adapterType="BaseValidatorControlAdapter" />
</controlAdapters>
</browser>
</browsers>
My question for you is. Is it possible for me to set the default value of Display for any validator control. Because my current solution just overrides what there is right now and there is no way of changing that. Therefor when the situation arrises that I do need something else then dynamic in the display option there is no solution for it.
I'm almost convinced that there is a better solution to this.
Any advice is appreciated!
Edit august 2nd 2012:
I finally settled with the solution to override the default asp.net controls and add the following constructor to them
public controlname ()
: base ()
{
this.Display = "Dynamic";
}
I added all these controls to a namespace and now I can do
<validator:RequiredField ID="RqrdFld_x" runat="server" Display="Static" />
Essentially overriding the default value in my control definition and overriding the default control Display value of Dynamic in the constructor.
This link should be helpful in solving your problem.
You can use a skin file to set defaults for web controls accross a .NET site.
I have added a folder called DefaultTheme to my App_Theme folder and added a file to it called Skin.skin, with the following contents:
<asp:RequiredFieldValidator runat="server" Display="Dynamic" />
<asp:CompareValidator runat="server" Display="Dynamic" />
<asp:RegularExpressionValidator runat="server" Display="Dynamic" />
..allowing me to have a default setting for a number of different validators (or other controls) across my website.
What you can do then use such code in Page_Init event:
foreach(Control control in Page.Controls){
if(control is System.Web.UI.WebControls.BaseValidator)
{
control.Display = "Static";
}
}
It will find all the controls and set the Display property accordingly.

Dynamic data load on ASPX page

I have an internal web service (ASP.NET) written on C# in a company I work for. There are only 2 pages in it, one of this pages contains DropDownList.
Every time when user selecting an item from that DropDownList I need to somehow pass selected item value to a static method and show result string of that method anywhere on page.
I've never worked with ASP.NET or any web programming before and a bit confused about how to do it, not sure where to start looking even.
In your aspx file you should have this:
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
onselectedindexchanged="ListBox1_SelectedIndexChanged"></asp:ListBox>
Notice the AutoPostBack="True" which goes back to the server and fires the selectedindexchanged event immediately after the user changes the selection in the listbox
In your code-behind (.cs file)
You should have this:
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// Call static method and pass the ListBox1.SelectedIndex
// MyStaticMethod(ListBox1.SelectedIndex);
}
you can either se5t the autoPostBack="true" and handle the change event on the server side or using jQuery subscribe for the change event and get the value on the client side
You should probably check out some of the great resources that microsoft provides for new .NET developers. They will be really helpful in getting you started. Her is a link of some really good videos to help you out: http://www.asp.net/web-forms/videos
Not sure what language you are coming from, if any... But for the most part webforms is going to work a lot like other web based methodologies.
Your ASP.NET Controls (in your case the DropDownList) have both client and server side events.
You will probably want to map the server-side OnSelectedIndexChanged event on your DropDownList.
In order to cause a postback on that control you will want to set the AutoPostBack property to true on your DropDownList.
try this one
In html ,
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
In aspx.cs page,,
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selctedValue = DropDownList1.SelectedValue;
/// Call yours static methid here
YourMethod(selctedValue);
}

CustomValidator ServerValidate method does not fire

I've put a CustomValidator on my form. I have not set its ControlToValidate property. In its ServerValidate event I've written the following:
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
args.IsValid = false;
}
I put a breakpoint to this method but it seems to never come to that point. But if I do this on another form it works like a charm.
The ValidationGroup property of both the button and the CustomValidator are the same
I tried deleting this property in both the button and the CustomValidator, still does not work.
It seems as there's something formwide. I just put a CustomValidator on the form and do not touch any of its properties other than just setting its ServerValidate event method.
EDIT: Here's the aspx part:
<asp:CustomValidator ID="CustomValidator2" runat="server"
ErrorMessage="This is a test"
onservervalidate="CustomValidator1_ServerValidate"
ValidationGroup="PA"></asp:CustomValidator>
<asp:Button ID="btnPensionersOK" runat="server" Text="OK" Width="75px"
onclick="Button1_Click" ValidationGroup="PA" />
Try to force the validation in the button-click handler via Page.Validate:
protected void Button1_Click(Object sender, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
// servervalidate should have been called
}
}
Edit(from comments):
If you want the customvalidator to validate if nothing was entered/selected in your controls, you need to set ValidateEmptyText to true. You also might want to let the CustomValidator replace the RequiredFieldValidators.
I assume that the validator-order on the aspx decides whether or not a customvalidator's severvalidate is called if a previous Validator already has made Page.IsValid=false. Or ASP.NET is so smart that it assumes the SeverValidate to be costlier than a simple text-is-empty check.
I would also like to put some more help for those who will use CustomValidators and RequiredFieldValidators at the same time. One should take into account that Client side validation takes place first. And the server side validation will occur only after PostBack. I'm sure you got it but just in case this is not quite clear: It means first all the controls that are bound to certain client side working validators must be valid to let Postback to occur. After Page. IsValid is True server side stuff takes place and posts back any changes which includes server side validation messages.
So here are the ways one can make both CustomVCalidators and other built in validators to work at the same time.:
Set both groups of validators to work on Client side. In this case we must ensure that for the custom valitor(s) we spacify the script that will make validation on the client side. Without writing script and just filling in the ServerValidate method the validation will take place in the server.Even if EnableClientScript property is set to True.
Set both groups of validators to work on server side. To do so simply set EnableClientScript to False. But note that this will load the server.

Categories