Web to lead: requiring fields with Javascript validation

In a previous post, I talked about a few ways that I customize web-to-lead forms. One key change I make is to ensure that certain fields get filled in for every web lead. In a Salesforce page layout, you can require fields, but web-to-lead doesn’t allow you to do this - any web-to-lead form submission will create a lead, even if critical fields such as last name or email are left blank.

Most of our clients want to make sure their leads fill in a minimum amount of information, such as name and email. Moreover, you can catch spam by requiring sensible entries - since spammers don’t always fill in the fields.

Javascript lets you review a form submission before sending it. To use the feature, you provide a Javascript function for the onsubmit event in the web-to-lead form tag:

<form
  action="https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8"
  method="POST" onsubmit="return validate(this)">

The Javascript code goes in a <script> block within the <head> section of the web page:

<script language="JavaScript" type="text/JavaScript">
<!--
//Written by Evan Callahan, NPower Seattle
function validate(theForm) {
  // add the name of each field you want to require
  // for custom fields, use the Salesforce field ID
  var required = ["first_name", "last_name", "email", "00N50000001bPCT"];
  var invalid = false;
  for (var i in required) {
    var theField = theForm[required[i]];
    if (theField.value == “”) {
      theField.parentNode.className = “invalid”;
      if (!invalid) theField.focus();
      invalid = true;
    } else {
      theField.parentNode.className = “”;
    }
  }
  if (invalid) {
    alert(”Please enter a value in the highlighted fields.”);
    return (false);
  } else {
    return (true);
  }
}
//–>
</script>

If any of the fields you specify are left blank, the web browser displays an alert and the required fields appear with a red line at the left edge (similar to the style Salesforce uses for required fields).

Two important notes if you want to use this: First, the function depends on a style definition to show a red line at the left edge of a field. To define the style, add this <style> block in the <head> section of the web page:

<style type="text/css">
   <!--
   .invalid { border-left: 3px solid red; }
   -->
</style>

Secondly, the function assumes that you’ve formatted the web to lead fields in a table. The code applies the “invalid” style to the cell (the <td> tag) containing the field, not to the field itself. This is important if you want to require a value in picklist fields, because picklist boxes can’t have a colored left border in Internet Explorer.

Leave a comment

Please be polite and on topic. Your e-mail will never be published.