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

1

6

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:

A screenshot of an HTML5 validation error message showing the current value of a counter input is not within valid bounds

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.NET 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 infrastructure 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

Empathy answered 17/9, 2013 at 20:11 Comment(10)
I assume the submit event would have not been fired anyway - it only fires when the user submits a form (so formElement.submit() does not trigger it, as far as I remember) and a form submission (not initiated by JavaScript) requires the form to have a type=submit (input or button) anywhere.Multiplicity
I guess a hacky solution can be found here - experts-exchange.com/Programming/Languages/Scripting/JavaScript/…Multiplicity
A better solution would be to add a custom validator - msdn.microsoft.com/en-us/library/a0z2h4sw.aspxMultiplicity
@Multiplicity Custom validators seem to run on the server.Empathy
The article mentions custom client side validations as well.Multiplicity
@Multiplicity custom validators are an ASP.NET MVC thing, this is web-forms.Aila
@Aila - the article does not mention MVC in any way, but it does mention Web Forms - "Walkthrough: Validating User Input in a Web Forms Page", so I am not sure what you mean here.Multiplicity
@Multiplicity no biggy, I was just commenting that "Custom Validators" are only available in an MVC App, in web-forms there not called "Custom Validators" it's called "The Server Validation API" , that's not to say there not useable however, Like everything .NET you can add the MVC assemblies to a Web-Forms app, and give yourself the ability to use "Custom Validators" , but "Custom Validators" as a thing are not available in Web-FOrms only in MVCAila
@Aila - I still disagree with your comment, as the linked page specifically talks about Web Forms and uses the term Custom Validators as part of Web Forms.Multiplicity
@Multiplicity - your more than welcome to disagree :-) I have no problem with that, but the fact doesn't change that "Custom Validators" are from a technology level implemented by Microsoft not available in Web-Forms only the "Server Validation API" is unless you take extra out of the ordinary steps to make use of them.Aila
A
1

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.

Aila answered 6/7, 2014 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.