This site contains the document for old version. Please upgrade to the latest version v1.0.0

Contact form

Examples

A contact form is one of most popular form in every web sites. This example introduces steps to make a contact form:

Validating a contact form

A contact form need to collect some useful information from visitors. The following table shows a collection of popular information and the validators that are used to validate the associated input:

Information Validators
First and last name notEmpty
Phone number regexp. You can use the built-in phone validator
Email address notEmpty, emailAddress
Message notEmpty, stringLength
Captcha callback
The example demonstrates a way of generating a simple math calculation captcha. Anyway, you're recommended to use recaptcha2 add-on that supports Google reCAPTCHA.
<form id="contactForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-xs-3 control-label">Full name</label>
        <div class="col-xs-4">
            <input type="text" class="form-control" name="firstName" placeholder="First name" />
        </div>
        <div class="col-xs-4">
            <input type="text" class="form-control" name="lastName" placeholder="Last name" />
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label">Phone number</label>
        <div class="col-xs-5">
            <input type="text" class="form-control" name="phoneNumber" />
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label">Email address</label>
        <div class="col-xs-5">
            <input type="text" class="form-control" name="email" />
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label">Message</label>
        <div class="col-xs-9">
            <textarea class="form-control" name="message" rows="7"></textarea>
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label" id="captchaOperation"></label>
        <div class="col-xs-3">
            <input type="text" class="form-control" name="captcha" />
        </div>
    </div>

    <div class="form-group">
        <div class="col-xs-9 col-xs-offset-3">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    // Generate a simple captcha
    function randomNumber(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }

    function generateCaptcha() {
        $('#captchaOperation').html([randomNumber(1, 100), '+', randomNumber(1, 200), '='].join(' '));
    }

    generateCaptcha();

    $('#contactForm')
        .formValidation({
            framework: 'bootstrap',
            icon: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                firstName: {
                    row: '.col-xs-4',
                    validators: {
                        notEmpty: {
                            message: 'The first name is required'
                        }
                    }
                },
                lastName: {
                    row: '.col-xs-4',
                    validators: {
                        notEmpty: {
                            message: 'The last name is required'
                        }
                    }
                },
                phoneNumber: {
                    validators: {
                        notEmpty: {
                            message: 'The phone number is required'
                        },
                        regexp: {
                            message: 'The phone number can only contain the digits, spaces, -, (, ), + and .',
                            regexp: /^[0-9\s\-()+\.]+$/
                        }
                    }
                },
                email: {
                    validators: {
                        notEmpty: {
                            message: 'The email address is required'
                        },
                        emailAddress: {
                            message: 'The input is not a valid email address'
                        }
                    }
                },
                message: {
                    validators: {
                        notEmpty: {
                            message: 'The message is required'
                        },
                        stringLength: {
                            max: 700,
                            message: 'The message must be less than 700 characters long'
                        }
                    }
                },
                captcha: {
                    validators: {
                        callback: {
                            message: 'Wrong answer',
                            callback: function(value, validator, $field) {
                                var items = $('#captchaOperation').html().split(' '),
                                    sum   = parseInt(items[0]) + parseInt(items[2]);
                                return value == sum;
                            }
                        }
                    }
                }
            }
        })
        .on('err.form.fv', function(e) {
            // Regenerate the captcha
            generateCaptcha();
        });
});
</script>

Sending email with Mandrill API

Mandrill provides a reliable, secure delivery API for transactional emails from websites and applications. It's easy for developers to integrate sending emails with its API which are available in various programming languages.

The following piece of code uses an Ajax request to send the needed information to Mandrill API:

<form id="contactForm" method="post" class="form-horizontal">
    <!-- This container will be shown after sending new message -->
    <div id="alertContainer" class="alert" style="display: none;"></div>

    <!-- Form fields -->
    ...
</form>
$('#contactForm')
    .formValidation({
        ...
    })
    .on('success.form.fv', function(e) {
        // Prevent default form submission
        e.preventDefault();

        // Change these values to match with your application
        var MANDRILL_API_KEY = 'YOUR-MANDRILL-API-KEY',
            EMAIL_SUBJECT    = 'Contact form',
            RECEIVER_EMAIL   = 'hello@formvalidation.io';

        var $form = $(e.target),
            // Generate a message based on submitted form data
            body  = [
                '<strong>Name:</strong> ' + $form.find('[name="firstName"]').val() + ' ' + $form.find('[name="lastName"]').val(),
                '<strong>Phone number:</strong> ' + ($form.find('[name="phoneNumber"]').val() || 'n/a'),
                '',
                '<strong>Message:</strong> ',
                $form.find('[name="message"]').val()
            ].join('<br/>');

        // Send the message
        $.ajax({
            type: 'POST',
            url: 'http://mandrillapp.com/api/1.0/messages/send.json',
            contentType: 'text/plain',
            dataType: 'json',
            data: {
                key: MANDRILL_API_KEY,
                message: {
                    from_name: $form.find('[name="fullName"]').val(),
                    from_email: $form.find('[name="email"]').val(),
                    to: [
                        {
                            email: RECEIVER_EMAIL,
                            'type': 'to'
                        }
                    ],
                    auto_text: true,
                    subject: EMAIL_SUBJECT,
                    html: body
                }
            }
        }).done(function(response) {
            // Clear the form
            $form.formValidation('resetForm', true);

            // Regenerate the captcha
            generateCaptcha();

            // Show the message
            response.status === 'error'
                ? $('#alertContainer')
                    .removeClass('alert-success')
                    .addClass('alert-warning')
                    .html('Sorry, cannot send the message')
                    .show()
                : $('#alertContainer')
                    .removeClass('alert-warning')
                    .addClass('alert-success')
                    .html('Your message has been successfully sent')
                    .show();
        }).fail(function(jqXHR, textStatus, errorThrown) {
            $('#alertContainer')
                .removeClass('alert-success')
                .addClass('alert-warning')
                .html('Sorry, cannot send the message')
                .show();
        });
Due to the cross domain issue, the Ajax request above doesn't work on the Internet Explorer (IE) browser version 8, 9. In order to support these IE versions, you should take a look at the jQuery-ajaxTransport-XDomainRequest script.

Although the code above doesn't require to touch your server side, the visitors can view the source and use your API key. To avoid that, you can send the form data to your back-end first:

$('#contactForm')
    .formValidation({
        ...
    })
    .on('success.form.fv', function(e) {
        // Prevent default form submission
        e.preventDefault();

        var $form = $(e.target);

        // Send all form data to back-end
        $.ajax({
            url: '/path/to/your/send-mail.php',
            type: 'POST',
            data: $form.serialize(),
            dataType: 'json',
            success: function(response) {
                // Clear the form
                $form.formValidation('resetForm', true);

                // Regenerate the captcha
                generateCaptcha();

                 // Show the message
                response.result === 'error'
                    ? $('#alertContainer')
                        .removeClass('alert-success')
                        .addClass('alert-warning')
                        .html('Sorry, cannot send the message')
                        .show()
                    : $('#alertContainer')
                        .removeClass('alert-warning')
                        .addClass('alert-success')
                        .html('Your message has been successfully sent')
                        .show();
            }
        });
    });

And then the back-end sends the email using Mandrill API. The following code shows how to do it with PHP:

<?php
// send-mail.php

// Download Mandrill PHP library from
// https://bitbucket.org/mailchimp/mandrill-api-php/get/master.zip
require_once '/path/to/Mandrill.php';

try {
    // See https://mandrillapp.com/api/docs/index.php.html
    $mandrill = new Mandrill('YOUR-MANDRILL-API-KEY');

    // Build the message body
    $body     = array(
        '<strong>Name:</strong> ' + $_POST['firstName'] + ' ' + $_POST['lastName'],
        '<strong>Phone number:</strong> ' + isset($_POST['phoneNumber']) ? $_POST['phoneNumber'] : 'n/a',
        '<strong>Message:</strong> ',
        $_POST['message'],
    );
    $body     = implode('<br/>', $body);

    $message  = array(
        'html'       => $body,
        'subject'    => 'Contact form',
        'from_email' => $_POST['email'],
        'from_name'  => $_POST['firstName'] + ' ' + $_POST['lastName'],
        'to'         => array(
            array(
                'email' => 'change-to-your-email-address@domain.com',
                'name'  => 'Change to your name',
                'type'  => 'to'
            )
        ),
        'headers'    => array(
            'Reply-To' => 'message.reply@example.com'
        ),
    );
    $async  = false;
    $result = $mandrill->messages->send($message, $async);

    echo json_encode(array(
        'result' => 'ok',
    ));
} catch(Mandrill_Error $e) {
    echo json_encode(array(
        'result' => 'error',
    ));
}