.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Custom Validator and Postback

Posted By:      Posted Date: October 08, 2010    Points: 0   Category :ASP.Net

Hello frnds

I have used custom validator in my asp.net website

I am using server side validation 

my page contains a textbox (txtName), and 2 combobox (CmbState and CmbCity) and some more controls

Now i want to validate my page using custom validator only when save button is clicked.

one of my combobox has implemented SelectedIndexChanged event. so whenever i change a value in that combobox, instead of firing SelectedIndexChanged event, my validation is fired and it is displaying error message of custome validator.

i want to do validation only when save button is clicked and not when postback is done by any of my controls on that page.

How can i do this? is there any way to do this?



View Complete Post

More Related Resource Links

Custom Validator


I need to validate a field that depends from a selection of a dropdownlist.

Like, if on dropdown the selected value is 'N' then validate. But it it's 'S', ignores validation;

Is there a way to do this with custom validator ??

I tried but, it's not working.

function chkEndereco(source, args){
   var cmbOnde = $('select[id$=comboOnde]');
   if(cmbOnde.val() == 'N')
      args.IsValid = (args.Value == '')
   if(cmbOnde.val() == 'S')
     args.IsValid = true

<asp:TextBox ID="Endereco" name="endereco" runat="server" AutoCompleteType="none" autocomplete="off" />
                                    <ajaxToolKit:TextBoxWatermarkExtender ID="wmEndereco" runat="server" TargetControlID="Endereco" WatermarkText="Endereço (rua, avenida, etc)" />
                                    <asp:RequiredFieldValidator ID="rqEndereco" runat="server" ErrorMessage="Ops! Faltou o endereço." EnableClientScript="true" ControlToValidate="Endereco" Display="None"/>
                                    <asp:CustomValidator ID="crqEndereco" runat="server" ErrorMe

Creating a Validator class for a custom activity

I created a new Workflow Activity Library and then added a new Activity called BindForm2Activity. After that I added a new class called BindForm2Validator and then placed an attribute to the BindForm2Activity to link it to the validator class.   Here is the code for each of the classes:   BindForm2Activity.xoml.cs: Code Snippet   using System;using System.ComponentModel;using System.ComponentModel.Design;using System.Collections;using System.Drawing;using System.Linq;using System.Workflow.ComponentModel.Compiler;using System.Workflow.ComponentModel.Serialization;using System.Workflow.ComponentModel;using System.Workflow.ComponentModel.Design;using System.Workflow.Runtime;using System.Workflow.Activities;using System.Workflow.Activities.Rules; using FormsCollection;using Utils; namespace ActivityLibrary{    [ActivityValidator(typeof(BindForm2Validator))] public partial class BindForm2Activity : SequenceActivity {        public static DependencyProperty FormToBindProperty = System.Workflow.ComponentModel.DependencyProperty.Register("FormToBind", typeof(FormsCollection.Form2), typeof(BindForm2Activity));         [Description("Form to bind a datasource to it ")]        [Category("BindForm2ToDataSource")]        [Browsable(true)]        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]        public FormsCollection.Form2 Form

custom validator

Is it possible to pass the maximum character length to validateCharacter, rather than just have it set in stone.<asp:CustomValidator ID="ValCharacter" ControlToValidate="txtCharacter"  OnServerValidate="validateCharacter"  Text="Too many characters" runat="server" Display="Dynamic" />        Protected Sub validateCharacter(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)        Dim iChars As Integer = 500        If args.Value.Length > iChars Then            args.IsValid = False        End If    End Subthanks.

Custom Validator on DDL&Textbox values

I need to write a 2 custom validators that works as follows: I have a formview (Formview1) with an EditItemTemplate. The validators need to validate values in "DropDownList1" and a textbox called "EndUserGUIDTextBox" If the value in DDL1 is ("Assigned" or "Assigned to End User") and the value of EndUserGUIDTextBox is ("unassigned" or "pending" or NULL) then I need a validator to fire and return {"GUID must be assigned when status is" & DLL1 value}. If the value in DDL1 is ("In Stock" or "In Repair") and EndUserGUIDTextBox is NOT ("unassigned" or "pending" or NULL), then I need a validator to fire and return {"GUID must not be assigned when status is" & DLL1 Value}. The validators needs to run and show in the formview when the UpdateButton in my Formview is clicked. I'm doing this in VB. Real noobie here! All help appreciated. Thanks,

Custom Validator inside PasswordRecovery...

Hello,   I am using a PasswordRecovery Control and have changed one of the validators to a custom Validator, however, OnServerValidate neer seems to get called.   Can someone tell me how to get the OnServerValidate to work correctly?   Thanks.

Problem with custom onBeginRequest-Handler on client-side when partial postback is triggered from ja

Hi, I have a Modal Dialog with a Ribbon, which starts a long running serverside operation. To inform the user about the progress, I implemented Dino Espositos "Progress Monitor Framework", which worked perfectly (after some work) - at least when I trigger the partial postback from a control inside the UpdatePanel used for displaying the progress. In this approach custom onBeginRequest and onEndRequest-Handlers are used to start and stop displaying the current status of the serverside operation. When I start the operation from a Button on the ribbon by doing "something" with the mentioned control via javascript the serverside operation is started, but my onBeginRequestHandler ist not called and the progress monitor is not "switched on" on the client. Here is what I´m doing in my javascript :  function pageLoad() { progressManager = new VCSharePoint.MultiEdit.Progress(); // Remove existing handlers Sys.WebForms.PageRequestManager.getInstance().remove_beginRequest(onBeginRequest); Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(onEndRequest); // Register handlers for UpdatePanel client events Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(onBeginRequest); Sys.WebForms.PageRequestManager.getInstance().add_endRequest(onEndRequest); } // onBeginRequest() // Called w

unable to trace value after postback within Custom Server Control

public class TextBox : AStateManagement, IControl { #region "Variables" #region "Local Variables" protected System.Web.UI.WebControls.WebControl _TextBox = null; protected string _CssClass = string.Empty; protected string _Text = string.Empty; protected bool _Visible = true; protected bool _Enabled = true; protected string _ID = string.Empty; protected bool _IsViewStateLoaded = false; #endregion "Local Variables" #region "Global Variables" #endregion "Global Variables" #endregion "Variable" #region "Constructor" public TextBox() { _TextBox = new System.Web.UI.WebControls.TextBox(); _TextBox.ID = this.UniqueID; } #endregion "Constructor" #region "Events" #endregion "Events" #region "Disposable" #endregion "Disposable" #region "Properties" public override string CssClass { get { return _CssClass; } set { _TextBox.CssClass = _CssClass = value; } } public virtual string Text { get { return _Text; }

custom validator firring on text changed


hi all i have a custom validator i have written a javascript method for this validator;

this validator has been pot on a textbox that has auto post back is true .... now this validation  fires when the post back happens...

i dont want it to fire on the post back but only on button click

please suggest 

thanks in advance 


How to Make a custom property or a page persist across postback



As the title suggests, I have an object to hold some specific state information in my web application - I pass it back & forward between pages by making it a property of a basepage which works fine, but I lose it on postback.

Is there any way to persist this property without manually adding & reading it again from viewstate?



Compare Validator not displaying message after postback


Hi all,

I have compare validators that I build on the fly in code behind that validate textboxes that are also built up in the code behind:

CompareValidator CV = new CompareValidator();
CV.ID = "CV" + parameter.Name;
CV.Type = ValidationDataType.Date;
CV.Operator = ValidationCompareOperator.DataTypeCheck;
CV.ErrorMessage = "* Invalid date";
CV.Display = ValidatorDisplay.Static;
CV.ControlToValidate = parameter.Name;
CV.ValidationGroup = "valGroup1";
CV.Style["font"] = "Arial";
CV.Style["color"] = "Red";
CV.Style["font-size"] = "10px";
CV.EnableClientScript = true;


These work fine until a postback occurs. After a postback they still validate the form (i.e. they don't let you postback) but the error message won't display. Can anybody please help?


Custom Validator



I have a C# web form (within a master page) and textbox - how do I validate it so that any input has to have a "AR" or "BR" prefix. I have started something along these lines:

                ARF Number
                <asp:CustomValidator ID="ValidatorArf" runat="server" ErrorMessage="PMO Ref!" ClientValidationFunction="jSValidate"
                    ControlToValidate="TextBoxArfNo" ValidationGroup="ValidationGroupCreateDesign"></asp:CustomValidator>
                <asp:TextBox ID="TextBoxArfNo" runat="server" MaxLength="50" />

Is this the best way forward? How do I write the validation script?

Thanks in advance!

Restore List of custom objects on postback


I have a model containing a List with custom objects, let's say Customer objects. Like this:

public class MyModel
public List<Customer> { get; set;}

public class Customer
public int id { get; set;}
public string name { get; set;}

In the View I print out (for simplicity) the name and id of the customer objects on the model. How to restore these values on postback if the method signature looks like this:

public Index(MyModel model)
...here model.Customer[x].Id and model.Customer[x].Name is null...

Should I use hidden values? This is not possible if the List contains items of interface type, for example List<ICustomer> where ICustomer is an interface. Is there any other way to "save" the values on each postback? For example I may want to view validation error messages when the user submits the form and then the properties of the customer object must still be there..

can anyone help me please - validator in modal popup prevent my button from postback


i have a very strange problem

for some reasons
i m forced to use the following solution

i have a situation that includs
a validation control
inside a usercontrol
that is loaded on the page using a modalpopup
when i click a button from inside a gridview

the problem is that the button inside the modalpopup
never fire the server code behind
as if the validator prevent it from doing so

my example website is uploaded here


anybody help me please


custom control validator - can't set width property


 I am trying to set the width property of a custom control validator but it is not happening at all. The width of the validator control popup is constantly 100% width (the width="200px" below has NO effect at all)

here is my code:

 < asp:RequiredFieldValidator id="RqdDateChange" 
ControlToValidate="txtDateChange" ErrorMessage="<b>Required Field Missing</b><br />The Date of Change is required.&quo

Custom TreeNode: how to implement postback?


I use a TreeView to display a sitemap, but I wanted next to every link a small image; when clicked, it would add the link to a list of favorites in the Profile of the site user.

So I made a custom TreeNode, but I cannot figure out how to make the image postback to the page and expose an event that I can capture and use to add the link to the Profile.

Looked around here and via google, but somehow no one ever seems to have done this. Can anyone help out?

Custom control's children do not persist contents after postback


I have created a really simple custom control to render panels into a page.  The code is below.  When I use my control and add any webcontrol to it, after each page postback the contents of these child controls vanishes.

I must have missed something really simple but please run the example to reproduce this.  Can anyone please enlighten me as to why the controls are being 'emptied' of their contents, and how I stop this occuring?

Crude diagram

Here is the code for the control

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

<ToolboxData("<{0}:MyTestControl runat=server></{0}:MyTestControl>"), ParseChildren(True)> _
Public Class MyTestControl
	Inherits CompositeControl
	Implements INamingContainer

	<NotifyParentProperty(True), PersistenceMode(PersistenceMode.InnerProperty)> _
	Public Property Panels() As List(Of Panel)
			Dim s As Object = ViewState("_StaticPanels")
			If s Is Nothing Then
				s = New List(Of Panel)
			End If
			Return CType(s, List(Of Panel))
		End Get
		Set(ByVal value As List(Of Panel))
			ViewState("_StaticPanels") = value
		End Set
	End Property


Custom Controls in C# .NET

Embedding user controls in a Windows form is just like adding a simple button or text box that are already provided with .NET. These basic controls were written essentially like you code your own controls. Typically the controls you design are to be used in multiple forms or to modularize your code. These reasons help reduce the amount of code you have to type as well as make it easier for you to change your implementation. There should almost never be any reason to duplicate code because it leaves a lot of room for bugs. So, implementing functionality specific to your control in the control's source code is a good idea. This reduces code duplication as well as modularize your code, which is a good programming guideline.
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend