EW Resource

JavaScript Form Validation

HTML5 Form Validation - with a cross-browser shim

HTML5 has made client-side form validation very simple. The form input elements now have a 'required' parameter and when this is added, validation is automatic.

So what do we do for older browsers, typically older versions of IE, which don't automatically get upgraded like Chrome, Safari and Opera? Well, we use a Shim or Polyfill, which adds appropriate code in the background when the HTML5 support isn't there.

There are several shims for this and the one that appealed to me when I first came across it is the NWX Forms shim created by Diego Perini. Unlike some other shims, this doesn't need you to add extra classes to the form inputs, you simply add a reference to the hosted JavaScript file, add two lines of JavaScriot to call it, and the validation works from IE6 upwards.

You can read about it on GitHub but it's included in the HTML5 Snippets I have available for download.

Note: The NWX shim also supports the HTML5 'placeholder' property in old browsers.

Using FP2003 to create the code

The normal form field validation that was in FrontPage is not in Expression Web, unfortunately. The only validation available is with the ASP.Net validation controls, which aren't of use with normal html form fields.

Although it's possible to hand code the validation, you can open the form page in FP and add the validation there. You can then open the page in EW and the validation 'Bot' will still work.

What I often do though is preview the page in a browser, view the source, and then copy it over the original page code. This gives me the JavaScript that the FP Bot generates and allows me to edit the somewhat unhelpful messages it produces.

When you preview the page and copy the code you'll see something like this:

<script Language="JavaScript" Type="text/javascript">
function FrontPage_Form1_Validator(theForm) {
 if (theForm.txtName.value == "") {
alert("Please enter a value for the \"Name\" field.");
return (false); }
return (true); }

The error message can easily be changed by altering the 'alert' text to something more meaningful, eg:

alert("Please enter your full name.");

Using FP like this to generate the code is not an ideal solution but it's easier than hand coding or using some other tool.