New! We have a simpler method for adding validation to forms – view it here.

One of the more common questions we get asked is if you can make certain fields be required when people sign up to your list through a Campaign Monitor form.

We don’t have this functionality built in, mostly because you can create a much better experience for your visitors by taking care of that right there on your form page, rather than sending them off to a generic Campaign Monitor error page.

Most of you Campaign Monitor customers are smart cookies who have your own approach to error messages and server side scripting, and are happy to cook something up yourselves. However, sometimes it is just easier if you have something to start you off.

So here’s a basic javascript form validation script, which you can examine, copy, tweak or take as you like. It’s based on code from the excellent DOM Scripting book by Jeremy Keith, and should give you enough of an idea to work with.

Adding validation to your form

The first step is to take your subscribe form, and add a CSS class to define which fields will be required. You could make as many as you like required, but remember that the less work people have to do, the more likely they are to sign up.


<form action="http://abcwidgets.cmail1.com/s/133578/" method="post" onsubmit="return validateForm(this);" class="list-form">
<ul><li>
<label for="name">Name:</label> <input type="text" name="name" id="name" class="required" /></li>
<li><label for="l133578-133578">Email:</label> <input type="text" name="cm-133578-133578" id="email"  class="email required"  /></li>
<li><label for="cm-f-184432">Nickname:</label> <input type="text" name="cm-f-184432" id="Nickname" /></li>
<li class="sub-button"><input type="submit" value="Subscribe" /></li>
</ul>
</form>

You can see I’ve added class=”required” to the text fields I want to make compulsory, and class=”email required”> in the case of the email address. I’ve also added an onsubmit parameter to the form tag, which will run our validation function when the submit button is clicked.

Now we need to add some javascript into the head of the page with our form on it. Remember, you cannot change the form element names, because that will prevent the form working. You can change the ID of the elements though, if you need to refer to specific fields in your script.


<script type="text/javascript">
function validateForm(theform) {
 for (var i=0; i<theform.elements.length; i++) {
  var element = theform.elements[i];
  if (element.className.indexOf("required") !=-1) {
   element.className = "required";
   if (!isFilled(element)) {
    alert("Please enter your " +element.id);
    element.className += " error";
    element.focus();
    return false;
   } 
  }
  if (element.className.indexOf("email") !=-1) {
   element.className = "required";
   if (!isEmail(element)) {
    alert("Please check you have entered a valid email address");
    element.className += " error";
    element.focus();
    return false;
   }
  }
 }
 return true;
}

function isFilled(field) {
 if (field.value.length < 1) {
  return false;
 } else {
  return true;
 }
}
function isEmail(field) {
 if (field.value.indexOf("@") == -1 || field.value.indexOf(".") == -1) {
  return false;
 } else {
  return true;
 }
} 
</script>

Without getting too far into details about exactly how the script works, here’s the outline:

  • The function validateForm runs when the submit button is pressed
  • We loop through all the elements, looking for the ones with a class of ‘required’ or ’email’
  • When we find a required field, we check to see if it is empty, and if so, trigger an error and addan ‘error’ class to the field
  • If the field is an email field, we also run a simple check to see if it looks like a valid email
  • We return ‘true’, if all is well, and the form is sent, or ‘false’ if not, and the submit is cancelled

Note: I’ve only used alert messages here (and some CSS styling), which is not the ideal way to notify. You will probably want to write out an error message next to the problem field.

I’m also just notifying about one error at a time, which is fine for very small forms, but annoying for anything longer. If you have bigger forms, you’d want to create an array of the errors, and write them all out at once instead. A final note is that the script only deals with text fields – if you have dropdowns for example you need to modify your testing slightly.

That’s it! A very simple version of form validation to make sure people can’t leave key fields empty when signing up. Take it, and amend it to work for you or your clients.

  • Jacob

    I’ve written something similar for our use at Masterworks.

    I’ve never quite understood why front end form validation allows forms to be submitted if they aren’t valid, so my script disables the submit button, then adds “onchange” events to all the required fields. When they all have data the submit button is turned back on.

    I add a little note next to the button letting people know why its disabled.

    Another thing to note, is that this validation is front end only and you should be doing some back-end validation.

    Fortunately the Campaign Monitor API would allow you to do some back-end processing of the data and then submit it.

  • Mathew Patterson

    Thanks Jacob. You are right of course that backend validation is also key (and Campaign Monitor will validate the email address anyway).

    However, the set of people who are asking for help making fields required are probably not in a position to write backend validation code either, so baby steps!

  • Mark Wyner

    Client-side validation is great for quick responses that don’t require a hit/return from the server. However it is of the utmost importance that server-side validation is integrated for those with scripting disabled. Not doing so means either:

    a) the form can’t be submitted
    b) the form cant’ be validated when submitted

    The resulting scenario depends on how your client-side script is set up.
    But if you’re going to put client-side icing on your server-side validation, Jeremy Keith is the sensei to be consulted. His book DOM Scripting (as noted) is truly a gem.

  • Marc Wilson

    For more detailed editing, you could add a “mask=” attribute to the field and put a regex mask in it, and go beyond empty/not-empty validation. Actually, it’s a shame HTML doesn’t provide this level of validation automatically.

  • Jeremy Brown

    I much prefer this script, it validates as you go through the form rather than as the form is submitted.
    It uses Prototype to animate the messages.
    The best part of this you apply your error message in the input tag and apply classes of how you want it validated such as required, email, selected etc.

    Have a look at the demo, I am really only scratching the surface here.
    http://tetlaw.id.au/view/javascript/really-easy-field-validation

  • Spencer

    You’ve got some serious code stretching issues with your pre tags extending into the right column, at least that’s how it is in Firefox. If you add this bit of code to your pre in your CSS, it should prevent that code extending in all browsers.

    pre {
    white-space: pre-wrap; /* css-3 */
    white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
    white-space: -pre-wrap; /* Opera 4-6 */
    white-space: -o-pre-wrap; /* Opera 7 */
    word-wrap: break-word; /* Internet Explorer 5.5+ */
    }

  • Dave Greiner

    Cheers Spencer, thanks for the tip.

Want to improve your email marketing? Subscribe to get tips on improving your email marketing delivered to your inbox.
X

Join 200,000 companies around the world that use Campaign Monitor to run email marketing campaigns that deliver results for their business.

Get started for free