Custom Validator Dynamic ServerValidate Using Reflection

Jul 4, 2010

I have a UserControl which contains a TextBox and a CustomValidator. I would like to set the CustomValidator.ServerValidate to a method in the page that contains the UserControl I found this code which will allow me to dynamically set the custom validators validation function: cusvCustom.ServerValidate += new System.Web.UI.WebControls.ServerValidateEventHandler(MethodName);

The problem is that a string value won't work there. It needs to be a reference to the method. Is it possible to use reflection (or some other method) to get a valid reference to the parent controls method using only the string name of it? The reason I want to use the string value of the method name is so I can place the control on the page thusly: <uc1:TextBoxField ID="tbUserName" runat="server" CustomValidationMethod="ValidateUserName" />

WebUserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl.ascx.cs" Inherits="WebApplication1.WebUserControl" %>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Custom Validation Failed" OnServerValidate="CustomValidator1_ServerValidate" />
<asp:TextBox ID="TextBox1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Submit" CausesValidation="true" />
WebUsecControl.ascx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebUserControl : System.Web.UI.UserControl
{
public ServerValidateEventHandler Validating;
protected void CustomValidator1_ServerValidate(object sender, ServerValidateEventArgs e)
{
if (Validating != null)
Validating(sender, e);
}
}
}
TestPage.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestPage.aspx.cs" Inherits="WebApplication1.TestPage" %>
<%@ Register Src="~/WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:WebUserControl ID="WebUserControl1" runat="server" OnValidating="WebUserControl1_Validating" />
</div>
</form>
</body>
</html>
TestPage.aspx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class TestPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//WebUserControl1.Validating += WebUserControl1_Validating;
}
protected void WebUserControl1_Validating(Object sender, ServerValidateEventArgs e)
{
e.IsValid = false;
}
}
}

I did some research and I found Type.GetMethod and MethodInfo but I can't get them to work. Primarily because I don't know the type of the parent control and can't figure out how to get it. EDIT: My code for matt-dot-net. As you can see it's almost an exact duplicate of your code. For whatever reason it does not work for me as I have it here. When I click on the button the page reloads and is the same. When I un-comment the one line though and click the button then I see the error message.

View 1 Replies


Similar Messages:

Javascript - Dynamic Error Message For Custom Validator Clientside?

Mar 22, 2011

I am using a custom validator to call a javascript function for validation. My problem is that I need to be able to change the error message dynamically. Here is the code:

<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="fcnValid1"
ErrorMessage="" Display="None" ValidateEmptyText="True">
</asp:CustomValidator>

[code]....

View 1 Replies

How To Create The Custom Validator Instance That Is Linked To The Custom Validator

Dec 17, 2010

I created my custom validator in one project, something like that:

[Code]....

he composite control in another project. I added a reference of the custom validator project to the composite control project. I have a textbox in a composite control and I would like to validate this textbox by the composite control I created. But how can I do that? How can I create the custom validator instance that is linked to the custom validator I created?

View 1 Replies

MVC - Find Controllers With (Authorize) Attributes Using Reflection In C# Or Build Dynamic Site.Master Menus?

Jun 8, 2010

I'm currently writing a web app in ASP.NET MVC 1.0 (although I do have MVC 2.0 installed on my PC, so I'm not exactly restricted to 1.0) -- I've started with the standard MVC project which has your basic "Welcome to ASP.NET MVC" and shows both the [Home] tab and [About] tab in the upper-right corner. Pretty standard, right? I've added 4 new Controller classes, let's call them "Astronomer", "Biologist", "Chemist", and "Physicist". Attached to each new controller class is the [Authorize] attribute. For example, for the BiologistController.cs

[Authorize(Roles = "Biologist,Admin")]
public class BiologistController : Controller
{
public ActionResult Index() { return View(); }
}

These [Authorize] tags naturally limit which user can access different controllers depending on Roles, but I want to dynamically build a Menu at the top of my website in the Site.Master Page based on the Roles the user is a part of. So for example, if "JoeUser" was a member of Roles "Astronomer" and "Physicist", the navigation menu would say:

[Home] [Astronomer] [Physicist]
[About]

And naturally, it would not list links to "Biologist" or "Chemist" controller Index page. Or if "JohnAdmin" was a member of Role "Admin", links to all 4 controllers would show up in the navigation bar. Ok, you prolly get the idea... Now for the real question... Starting with the answer from this StackOverflow topic about Dynamic Menu building in ASP.NET, I'm trying to understand how I would fully implement this. (I'm a newbie and need a little more guidance, so please bare with me.) The answer proposes Extending the Controller class (call it "ExtController") and then have each new WhateverController inherit from ExtController.

My conclusion is that I would need to use Reflection in this ExtController Constructor to determine which Classes and Methods have [Authorize] attributes attached to them to determine the Roles. Then using a Static Dictionary, store the Roles and Controllers/Methods in key-value pairs. I imagine it something like this:

public class ExtController : Controller
{
protected static Dictionary<Type,List<string>> ControllerRolesDictionary;
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
// build list of menu items based on user's permissions, and add it to ViewData
IEnumerable<MenuItem> menu = BuildMenu();
ViewData["Menu"] = menu;
}
private IEnumerable<MenuItem> BuildMenu()
{
// Code to build a menu
SomeRoleProvider rp = new SomeRoleProvider();
foreach (var role in rp.GetRolesForUser(HttpContext.User.Identity.Name))
{
}
}
public ExtController()
{
// Use this.GetType() to determine if this Controller is already in the Dictionary
if (!ControllerRolesDictionary.ContainsKey(this.GetType()))
{
// If not, use Reflection to add List of Roles to Dictionary
// associating with Controller
}
}
}

Is this doable? If so, how do I perform Reflection in the ExtController constructor to discover the [Authorize] attribute and related Roles (if any) ALSO! Feel free to go out-of-scope on this question and suggest an alternate way of solving this "Dynamic Site.Master Menu based on Roles" problem. I'm the first to admit that this may not be the best approach.

View 2 Replies

Does A Custom Validator Have To Be Used With The Validator Callout Extender

Jul 6, 2010

I have a validator callout extender that works, it shows the callout box. But, it does a postback. It didn't do a post back the first time I clicked the button but it did for subsequent times. I read on the AJAX site that a custom validator must be used with this for it to work. I'm currently using this with a required field and regular expression validator. It works, the callout appears, but it doesn't work every time with out the post back.I posted this to see if there is a way to get this to work with a required field and regular expression validator, with out using a custom validator. I'm using the newest release of the toolkit, so I thought the documentation may be old, since the callout is appearing.

View 8 Replies

Custom Server Controls :: Custom Validator Client-side Validation Cannot Work?

Jan 13, 2010

I've been trying to get a custom validator component working that ensures at least one checkbox from a checkboxlist has been checked. I've been used some code I found on dotnetjunkies.com but the client-side validation didn't work. I've been attempting to modify it to get the client-side javascript validation to work with no luck. Basically, I compile the below code into a DLL and add it to my bin folder.

[Code]....

View 2 Replies

Forms Data Controls :: CustomValidator - ServerValidate Fires Twice?

Nov 24, 2010

I have a CustomValidator and has ServerValidate handler that does custom user input validation against values in database. The key point is the validator is inside of DetailsView. Using Asp.Net 2.0

Issue:

The ServerValidate handler is firing twice when I click a button inside the DetialsView. I am injecting a javascript to show my custom error message in a dialog. So due the event firing twice the dialog appears twice.

Reason for this behavior:

I am sure there isn't anything in my code doing this. It is how the DetailsView and Button control works. Similar issue is listed

here and "DenGn" has given some explanation.

I don't know if anything really exists that can stop this behavior. What I am going to do is use a counter and store it in session, then do the check to see if it is the second time fire, not to inject my script.

Does anyone have any better solution or any other valid reason why this is happening and how to stop it?

View 5 Replies

Web Forms :: How To Use Dynamic Validator Control

Apr 2, 2010

I am not able to find any Site which will tell how to use Dynamicvalidator control in asp.net 3.5 from scratch.

View 2 Replies

.net - Validator Throwing Error On One Of Dynamic JS Pages?

Sep 8, 2010

I have the following RegularExpressionValidator on one of my pages:

<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ControlToValidate="InKindTextBox"
ErrorMessage="The value entered for 'Cash' must be in a number format. Examples: 500.00, 500, $500, $50,000 or $500.00"
ValidationExpression="(?n:(^$?(?!0,?d)d{1,3}(?=(?<1>,)|(?<1>))(k<1>d{3})*(.dd)?)$)" >

But when it tries to validate it throws the error below from one of my dynamic JS pages.When I run this regex through regex texter it works fine. Am i doing something wrong here?

View 2 Replies

Set Width Of Custom Validator

Feb 11, 2010

Does anybody know of a way to set the width of a custom validtor so that the error message text will wrap if it exceeds the specified width? I have a user control that contains a custom validator which the containing page can set the error message on based on specific validation results. he user control sits within a table cell in a page. If the message is very long it simply prints the entire message on a single line ignoring any column widths that are set. I have tried setting the width property on the custom validator itself to no avail.

View 2 Replies

MVC :: How And When Custom Model Validator Is Used

Apr 29, 2010

I am trying to understand a little more about implementing a custom model validator. I have implemented a custom model validator (derived from DataAnnotationsModelValidator<T>) for my custom validation attribute in order to do validation on the client side as well. There is not much documented about DataAnnotationsModelValidator. Besides, implementing client-side validation when is it a good idea or needed to implement a custom model validator for a custom attribute?

A separate question - in trying to understand how and when a custom model validator is used by the framework I noticed that my custom validator is always created with the context (2nd parameter in DataAnnotationsModelValidator<T>'s constructor) being a ViewContext, although it is declared as ControllerContext. Will a validator ever be created with something else than a ViewContext, and if so, when?

View 2 Replies

Custom Validator Not To Trigger On The First Button?

Feb 10, 2010

I have two buttons on my page, the first page is View Button and the second is Update Button. View button display's member's personal profile. If I click on the view button, my custom validator automatically trigger, meaning, it automatically displays the error message. Whereas, the custom validator must trigger if I click on the Update button. How am be able to deal with this kind of problem.

View 6 Replies

Web Forms :: Custom Validator Is Not Getting Called?

Jan 20, 2011

here is the code "when i select a value from calender customvalidator is not called . . "

[Code]....

View 7 Replies

Web Forms :: Calling A Custom Validator

May 12, 2010

I have a custom validator, which I have set a property for, and I can access this validator from my MVC controller method. However, when I run the code, I am not seeing the error message on the page. My code in the controller method looks like this:

If (!bool)
{
this.view.customValidator.IsValid = false;
this.view.customValidator.Visible = true;
}

View 2 Replies

Web Forms :: Error While Using Custom Validator?

May 6, 2010

I am using Customvalidator control . I am giving client side validation function in it. On running it is giving error as: ValidationStream is not defined.

Following is the code:

<asp:CustomValidator ID="CustomValidator6" runat="server" ClientValidationFunction="validateDriveDate"

View 2 Replies

Determine Which Custom Validator Will Fire First?

Feb 10, 2010

I have two custom validators that are in the same validation group. This validation group is launched by one button. My question is, in what order will the custom validators fire in? It appears that the validator that is placed earlier in the aspx page fires first, but I don't want to rely solely on this.

View 2 Replies

Web Forms :: Custom Validator Is Not Working In Ie6?

Feb 9, 2011

<asp:TextBox ID="txtMobile" runat="server" MaxLength="11"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="fteMobile" runat="server" TargetControlID="txtMobile"
FilterType="Numbers" />

[code]...

View 2 Replies

Custom Validator For MaxLength Property Of Textarea

May 16, 2010

I have quite a few text area's on my page and am wanting to limit the number of characters for each one. However each one should be able to have its own maxlength (i.e. one could be 20 characters and the other could be 100 characters). My validation on the page is all done using custom validation as the built in validation of .NET is not extensible enough for me to display my validation errors how I want to display them. So this is what im wanting to do:

Make a custom validatorPass a MaxLength value from the custom validator into the javascript function, this value must also be accessible from the code behindI can then run client side and server side validation on each textbox control. The problem I am having is passing a MaxLength value to client side script and to server side. Is there a property on custom validators which I can use to pass values around? For instance in Javascript I would want the value of the MaxLength and also the id of the Div which will show the characters remaining, and server side I would need to know the MaxLength. I have done lots of research on this and cannot seem to find an answer.

View 8 Replies

Web Forms :: Custom Validator Text Cannot Disappear

Aug 10, 2010

I have a form with textbox for name and two dropdownlist for month and years. Textbox has Requiredfieldvalidator and the dropdowns has got ustomvalidator.Initially when i dont enter anything in the text box and leave the dropdowns with default "MM" for month and "YYYY" for year i get error message in the validation summary at top and asterisk next to the textbox and dropdowns. Once i enter some text in the textbox and focus is away from textbox the asterisk disappears but even though i hav selected a valid month and year the asterisk next to the dropdowns is not disappearing. Same problem with the radio buttons.

View 5 Replies

Web Forms :: How To Write Custom Validator For DropDownlist

Jan 25, 2011

In my page i have DropDownlist.I want to write Custom validator.How to write?

View 3 Replies

Checkbox Custom Validator With ValidationSummary Not Working?

Jan 25, 2011

I have the following validation which is working fine for the rest of my fields, but trying to get a custom validator to work as part of the validation summary for a checkbox but no joy.

This is what I have at the moment

<script language="javascript" type="text/javascript">
function ValidateTandCs(source, args)
{
args.IsValid = document.getElementById('<%= optIn.ClientID %>').checked;
}
</script>
<asp:ValidationSummary CssClass="highlight"
id="ValidationSummary1"
HeaderText="<p>Please amend these errors below to continue with your
application.</p>" Runat="server" />
<asp:CheckBox id="optIn" runat="server"></asp:CheckBox> I agree to the terms and
conditions of this site and I wish to Opt In for registration.
<asp:CustomValidator ID="valTandCs" ClientValidationFunction="ValidateTandCs"
ValidationGroup="ValidationSummary1" runat="server"
ErrorMessage="Please accept Terms and Conditions before submitting.">
</asp:CustomValidator>

But when I click submit I only see the error messages for my other fields and nothing for this checkbox..

View 1 Replies

Comparing Two Date Format Using Custom Validator

Dec 14, 2010

How to compare tow date in format using custom validator and else. I have java script function like as. I want to call this function by using custom validator as

< </ asp:CustomValidator id="CustomValidator2" runat="server" ControlToValidate = "tbMyDate1"
EnableClientScript="True" Display="Static" ClientValidationFunction="Compare" SetFocusOnError="True" >asp:CustomValidator>
function { document.getElementById( Compare()"lblrefdate").innerText="";var m_names = new Array(
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec");
var { { dispMM=i+1; } }
dispdate=document.getElementById("tbMyDate");var
dispDD=dispdate .value.split("-")[0];var s1=dispdate.value.split("-")[1];var
dispMM;var i=0;for(i=0;i<=m_names .length ;i++)if(m_names [i]==s1) var { {
refMM=j+1; } } dispYY=dispdate .value.split("-")[2];var
refdate=document.getElementById("tbMyDate1");var refDD=refdate.value.split("-")[0];var
s2=refdate.value.split("-")[1];var refMM;var
j=0;for(j=0;j<m_names .length ;j++)if(m_names[j]==s2)var
refYY=refdate.value.split("-")[2]; if {
document.getElementById(
} (isNaN (refYY))"lblrefdate").innerText=""; else { { { { {
document.getElementById(
} if(refYY<=dispYY)if(refMM <=dispMM )if(refMM==dispMM)if(refDD <=dispDD )"lblrefdate").innerText="";else { document.getElementById(
} } } "lblrefdate").innerText="Ref Date can Not Be Grater then Disp Date";else {
document.getElementById( } }
"lblrefdate").innerText="Ref Date can Not Be Grater then Disp Date";else
document.getElementById( { } } }
"lblrefdate").innerText="Ref Date can Not Be Grater then Disp Date";

View 2 Replies

C# - Custom Validator Firing But It Does Not Update The ValidationSummary

Nov 29, 2010

I am working on a custom form field validator, it seems like the custom validator is working by not allowing it to continue to the next page, but it doesn't update the Validation Summary nor does it display the asterisk and the labels that i've made visable. I also have other validators like RequiredFieldValidator on the same field. My ValidationGroup is set, as is the Text and IsValid. I even wrote and set a dummy client side validation method in javascript as some workarounds suggests.

here is the validation summary code in asp.net

[Code]....

View 1 Replies

WCF / ASMX :: WCF Username Authentication With A Custom Validator?

Feb 18, 2011

how to implement WCF username authentication with a custom validator in both client side and server side. I am trying this since last 2 days. but no result.

View 7 Replies

No Error Message Displayed For Custom Validator?

Nov 3, 2010

I have a requirement that one of multiple fields is required. Using custom validator the even fires, false is returned, but no error message is display and the form validates. What am I missing? I have tried with and without ValidationSummary.

<asp:CustomValidator ID="CustomValidator1" OnServerValidate="validatePhone" EnableClientScript="false" runat="server" ErrorMessage="Home or Cell Phone is Required" ></asp:CustomValidator>
<asp:ValidationSummary ID="ValidationSummary1" DisplayMode="BulletList" runat="server" ForeColor="Red" Font-Size="X-Small" Font-Bold="true" />
protected void validatePhone(object sender, ServerValidateEventArgs e)
{
e.IsValid = string.IsNullOrEmpty(txtCellPhone.Text) && string.IsNullOrEmpty(txtHomePhone.Text) ? false : true;
}

View 3 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved