Using Javascript to Enhance or Override Form Validation

Have you ever needed to alter the way a form validates user input, but couldn’t do so using PHP or HTML5’s (admittedly primitive) “required” attributes?

Well, here’s another approach you can try.

Normally, you would want to utilize PHP or any server-side scripting language to check the state of a form before allowing users to submit their input for further processing. However, in situations where you may not have direct access to a website’s filesystem, it is possible to leverage JavaScript as a secondary means of form validation.

We must stress that, because JavaScript is processed on the end user’s machine, you should never rely on it to validate sensitive information – JavaScript can always be disabled or otherwise tampered with, so the strategies outlined in this article are only truly useful where extra form validation would be convenient, or nice to have, but not mission critical.

So, how do we do it?

The key here is a JavaScript function called event.preventDefault(), which will effectively cancel an HTML action before it can begin.

In our case, we wanted to step through a registration form and verify that our user had selected at least one checkbox element from a number of independent categories. If our JavaScript-based validation failed, we would simply cancel the user’s submission request.

Here’s what we came up with:

jQuery(document).ready(function()
{
    document.getElementById("form-submit").addEventListener("click", function(event)
    {
        var found_checked = false;
        // Loop through checkboxes and see if any have been selected
        jQuery(".class-dates input").each(function()
        {
            if (jQuery(this).prop("checked"))
            {
                found_checked = true;
                return (false);
            }
        });
        // Stop form submission if necessary
        if (!found_checked)
        {
            event.preventDefault();
            alert("You must select at least one class.");
        }
    });
});

Let’s take a closer look at a few lines of code and explain how they work:

  • Line 3 – This will run our code when the user clicks on a webpage button with the id “form-submit”
  • Line 5 – We declare a variable (“found_checked”) that is used later in the snippet to see whether any checkbox was selected
  • Line 7 – We loop through all of the input fields (checkboxes) that are within a container called “.class-dates”
  • Lines 9-13 – If a checkbox is selected, we set our variable to true and break out of the loop
  • Lines 16-20 – If our variable is still set to false, that means no checkbox was selected, so we should abort the submission request with event.preventDefault()

Pretty simple overall, and our client was very happy with the results!

Of course, you are welcome to adapt the code to your needs. JavaScript is a powerful language – suitable for even the most complicated form validation setups – and as long as you are mindful of security implications, the sky’s the limit.

Browser Compatibility

The event.preventDefault() method is compatible with all modern browsers, however Internet Explorer 8 and below are not supported.

It is possible to use a variable called event.returnValue if you need to ensure proper functioning in older browsers, though it should be noted that our example code relies on the jQuery library, which is also incompatible with IE8. Luckily, this version of Internet Explorer only accounts for 0.4% of the worldwide browser market share, so compatibility is not essential for most projects.

Questions? We’re here to help.

If you have any questions or would like to enlist our help in writing custom scripts for your website, feel free to contact us here. Together, we’ll bring your ideas to life.

Automatically Assigning Users with the WordPress Importer

Recently, one of our clients enlisted our help with migrating thousands of WordPress posts to another server. At 515 Media, we like to use the official WordPress Importer plugin for such assignments – it reliably preserves all content formatting, and works perfectly in tandem with WordPress’ native XML generator.

Here’s the problem…

As much as we like the WordPress Importer, we ran into a frustrating limitation of the software this time around. You see, our client’s posts were authored by nearly 300 different user accounts, and the WordPress Importer tool did not automatically map these accounts to our new database.

Instead, the plugin will prompt you to create associations for each user by hand:

As you can imagine, this is quite a laborious process if you’re dealing with a database containing dozens or hundreds of published users! Our hearts go out to those of you who have had to map this many fields by hand – we’ve definitely been there before!

That’s why we came up with a simple JavaScript-based solution to completely automate the user assignment process. Today, we would like to share our code with all of you:

Our solution

// ==UserScript==
// @name         Import WordPress - Auto Assign Authors
// @namespace    https://515.media
// @version      0.1
// @description  Quickly fill out post authors
// @author       Eric Black of 515 Media
// @include       */wp-admin/admin.php?import=wordpress*
// @grant        none
// ==/UserScript==
var $ = window.jQuery;
$(document).ready(function() {
    $("#authors").before("<input type='button' id='auto-assign-authors' value='Automatically assign authors'>");
    $("#auto-assign-authors").click(function() {
        var missing = 0;
        $("#authors > li").each(function() {
            var full_author = $("strong",this).text();
            var this_author = full_author.substr(0, full_author.indexOf(' ('));
            var is_missing = true;
            $("select option",this).each(function(){
                if ($(this).text() == this_author) {
                    $(this).attr('selected', true);
                    is_missing = false;
                    return false;
                }
            });
            if (is_missing) missing++;
        });
        $("#auto-assign-authors").after("<p>Finished! Total fields without matches: " + missing + "</p>");
    });
});

 

You may install our code to any major web browser with an extension that manages userscripts. We recommend TamperMonkey for this purpose (Firefox / Chrome).

Simply choose to “Create a New Script” and paste our code into the TamperMonkey editor.

The next time WordPress Importer prompts you for user assignment, you will find a new button at the top of the page to fully automate the procedure:

In a matter of seconds, our script will populate every field without any further input.

Plus, in the event that some of your database’s usernames don’t quite match those from your imported XML, our script will tell you how many fields are still blank after the operation is complete (# of unmatched fields.)

You are more than welcome to use this script for free and adapt it to your needs. (We only ask that you don’t claim it as your own or try to profit from it!)

If you have any questions about the installation process or general usage, feel free to get in touch with us today. Also, don’t forget to check out our managed hosting plans if you want our help developing custom scripts for your own projects!