posted on Thursday, March 02, 2006 11:28 AM
by
leon
HowTo Skip Server Side Validation
ASP.NET button have nice property CausesValidation which allows to prevent client side validation when button clicked. Common, recomended pattern states that any validation performed on client should be done again at server. Suppose we use CustomValidator control with both client and server validation functions. We can bypass client validation using CausesValidation property, but we will be stoped by server validation. Would it be nice (logical) to bypass all validation on postback event raised by button with CausesValidation property set to false? Let's see how can we make this happen. The direct approach is to override Page.Validate method. in this method we'll check if event raised by button with CausesValidation=false and will call real Validate only if not. I probably could reproduce ASP.NET code used to retrieve from Request event source control, but here I am taking shortcut. We'll use private property of Page _registeredControlThatRequireRaiseEvent which is instantiated by ASP.NET. A bit of reflection at it's done:
public override void Validate()
{
Button btn = typeof(Page).InvokeMember("_registeredControlThatRequireRaiseEvent",
BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance, null, this, null, null) as Button;
if (btn != null && !btn.CausesValidation)
return;
base.Validate();
}