Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call HTML5 form.checkValidity during form.onSubmit in WebForms?

How can i override, or extend, the standard WebForms WebForm_OnSubmit javascript function?


I am using HTML5 input types in an ASP.net WebForms web-site. The user-agent (e.g. Chrome, IE, Firefox) already correctly handles data sanitization, alternate UI, etc.

Normally, when a user clicks an <input type="submit"> button, the User-Agent will halt the submit, and show UI to indicate to the user that their input is going to be invalid:

enter image description here

The problem with WebForms is that it does not use a Submit button. Instead, everything can be done through a javascript postback, rather than submitting the form:

 <asp:LinkButton ID="bbOK" Text="Save User" runat="server" OnClick="bbOK_Click"></asp:LinkButton>

Which, when rendered into client html, becomes a call to the Javascript:

WebForm_DoPostBackWithOptions(...)

With the really long form being an Anchor tag:

<a id="Really_Long_Thing_ctl00_bbOK" 
   href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$VistaToolbar$ctl00$bbOK", "", true, "", "", false, true))'>
   Save User
</a>

This means that the user-agent never gives the user a prompt that an entered element is invalid.

Even though the form is not being "submitted", it does still trigger an onsubmit event. I can manually trigger the HTML5 form validation using something like:

isValid = form.checkValidity();

Ideally i would hook that event in my ASP.web WebForms site:

Site.master

<form runat="server" onsubmit="return CheckFormValidation(this)">

<script type="text/javascript">
   function CheckFormValidation(sender) 
   {
      //Is the html5 form validation method supported?
      if (sender.checkValidity)
         return sender.checkValidity();

      //If the form doesn't support validation, then we just assume true
      return true;
   }
</script>

Except that the WebForms infrastructure deletes my onsubmit method handler, and replaces it with its own:

<form id="ctl01" onsubmit="javascript:return WebForm_OnSubmit();" action="UserProperties.aspx?userGuid=00112233-5544-4666-7777-8899aabbccdd" method="post">

So my own submit call is ignored. It appears that delving into WebForm_OnSubmit leads down a rabbit hole of ASP.net WebForms validation infrastructure:

function WebForm_OnSubmit() 
{
   if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) 
      return false;
   return true;
}

which calls the function:

var Page_ValidationActive = false;
function ValidatorOnSubmit() 
{
    if (Page_ValidationActive) {
        return ValidatorCommonOnSubmit();
    }
    else 
    {
        return true;
    }
}

which calls, which calls, which uses, which checks.

Just want HTML5 form validation with WebForms

The issue is that WebForms has a huge infrastrucure for checking a form before submitting, and displaying errors to users through a standardized mechanism (and entire infrastructure that i do not use). It takes over the onsubmit event of forms, and it doesn't (necessarily) use an <input type="submit"> in the process.

What can i do to convince ASP.net WebForms web-site to let the User-Agent validate the form?

See also

  • HTML5 validation and ASP.net Webforms
  • How do I get Client-side validation of ASP.Net page to run?
  • Trigger standard HTML5 validation (form) without using submit button?
  • MSDN Magazine: Better Web Forms with HTML5 Forms
like image 322
Ian Boyd Avatar asked Sep 17 '13 20:09

Ian Boyd


1 Answers

The web forms infrastructure deletes the handler because you attempt to add it directly on the element in the visual design environment, and web-forms is not designed to work this way.

Trapping the on-submit handler is easy, you just need to think a little creatively.

Whenever your trying to deal with anything like this in a web-forms environment, you have to learn to think about solutions that come after the web-forms page rendering pipeline. If you try to find a solution that works directly inside the web-forms engine, then web-forms will win every-time.

You can reproduce my exact test case here if you need too, or you can pick out the bits you need and re-use as required.

Step 1

Create a NEW web-forms project in C# (You can do it in VB if you want, but I'm putting my examples as C#), once your project has been created, right click on your application references, go into NuGet and install JQuery.

It is possible to do this with out JQuery, and just use native methods, but it's Sunday and I'm being lazy today :-)

Step 2

Add a new web-form to your project (using add new item) and call this 'Default.aspx', onto this form add some text, a text box a button and a label.

your code should look similar to:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jsvalidation.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    Please enter your name :
    <asp:TextBox ID="txtName" runat="server" data-jsname="username"></asp:TextBox>
    <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit"     />
  </div>
  <asp:Label runat="server" ID="lblResult">...</asp:Label>
  </form>

</body>
</html>

Then press F7 (or double click on the button) to go to the code behind editor for your form.

Step 3

Add your code for the button handler into your code behind. If your doing things exactly the same way as me, your code should look similar to this:

using System;

namespace jsvalidation
{
  public partial class Default : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {}

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
      if(Page.IsPostBack)
      {
        lblResult.Text = "Well hello there " + txtName.Text;
      }
    }
  }
}

At this point you can test things work by pressing F5, and what ever you enter (or don't enter) in the text box, should appear with the message in the label below when you press the submit button.

Now we have a basic web-forms set up, we just need to intercept the form submit.

Step 4

As I said a moment ago, you need to think outside the web-forms box.

That means you need to run your intercept AFTER the page has been rendered and sent to the browser.

All of the JS that web-forms injects into the mix is usually executed before the page output is allowed to proceed, which means before the opening body tag.

In order to get your code to run after it, you need to put your script at the END of the html output so that it runs last.

add the following code just before the closing body tag, but AFTER the closing form tag

<script src="/Scripts/jquery-2.1.1.js"></script>
<script type="text/javascript">

  $(document).ready(function() {

    $('form').submit(function() {

      var uninput = $('input[data-jsname="username"]');
      var username = uninput.val();

      if (username == "")
      {
        alert("Please supply a username!");
        return false;
      }

    });

  });

</script>

The more astute among you, will notice straight away that I'm not calling the HTML5 validation API, the reason is I'm trying to keep this example simple.

Where I check the username value is the important part.

All that matters is the anonymous function in which I perform the check returns true or false. (True is the default if you DON't return anything)

If you return a false, you'll prevent the post back taking place, thus allowing you to use whatever JS code you need to make the form fields change using the HTML5 validation API.

My personal preference is to use bootstrap (See the syncfusion free e-book range for my Bootstrap 2 book, and soon to be released Bootstrap 3 book), where you can use special markup and css classes in the framework such as "has-errors" to colour things appropriately.

As for the selection of the components using JQuery, well there's 2 things here you need to pay attention too.

  • 1) You should NEVER have more than one form on a web-forms page, in fact if I remember correctly, your app will fail to compile if you do, or at the most it'll certainly throw an exception at run-time.

  • 2) Beacuse you only ever have one form, then you can be very safe in making the asumption, that a generic 'form' selector in JQuery will only ever select your main form (Irrespective of the ID, name, lack or size thereof) and adding an onsubmit handler to it, will always attach this after web-forms has don'e it's thing.

  • 3) Beacuse web-forms can (and usually does) mangle ID names, it's generally easier to use 'data attributes' to add custom bits to your tags. The actual ASP.NET js side validation does this exact same trick itself to allow JS code and .NET code to happily co-exist in the same page. There are ways to tell .NET how to name the ID's but generally you have to set lots of options in lot's of places, and it's very easy to miss one. Using 'data attributes' and the JQ attribute selector syntax is a much safer, easier to manage way of achieving the same thing.

Summary

It's not a difficult task, but I have to admit, it's not one that's immediately obvious if your not looking outside the fence that web-forms builds around you.

Web-forms is designed for rapid application development, primarily for devs used to the desktop win-forms model. While web-forms still has it's place these days, for new greenfield apps I would recommend looking at other options too, esp ones that build on the foundations that the new HTML5 specifications are trying hard to lay down and get right.

like image 145
shawty Avatar answered Oct 15 '22 23:10

shawty