ASP.NET Web Forms Prompt Validator

For those still using Web Forms and Microsoft’s validation framework, like yours truly - and I know you’re out there! -, it is very easy to implement custom validation by leveraging the CustomValidator control. It allows us to specify both a client-side validation JavaScript function and a server-side validation event handler.

In the past, I had to ask for confirmation before a form was actually submitted; the native way to ask for confirmation is through the browser’s confirm function, which basically displays a user-supplied message and two buttons, OK and Cancel. I wrapped it in a custom reusable validation control, which I am providing here:

   1: [DefaultProperty("PromptMessage")]
   2: public sealed class PromptValidator : CustomValidator
   3: {
   4:     [DefaultValue("")]
   5:     public String PromptMessage { get; set; }
   6:  
   7:     protected override void OnPreRender(EventArgs e)
   8:     {
   9:         var message = String.Concat("\"", this.PromptMessage, "\"");
  10:  
  11:         if ((this.PromptMessage.Contains("{0}") == true) && (this.ControlToValidate != String.Empty))
  12:         {
  13:             message = String.Concat("String.format(\"", this.PromptMessage, "\", args.Value)");
  14:         }
  15:  
  16:         this.ClientValidationFunction = String.Concat("new Function('sender', 'args', 'args.IsValid = confirm(", message, ")')");
  17:         this.EnableClientScript = true;
  18:  
  19:         base.OnPreRender(e);
  20:     }
  21: }

A sample usage without any target control might be:

   1: <web:PromptValidator runat="server" PromptMessage="Do you want to submit your data?" ErrorMessage="!"/>

And if you want to specifically validate a control’s value:

   1: <web:PromptValidator runat="server" PromptMessage="Do you want to accept {0}?" ErrorMessage="!" ControlToValidate="text" ValidateEmptyText="true"/>

When submitting your form, you will get a confirmation prompt similar to this (Chrome):

image

                             

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website