FormValidation v0.8.1 is released, supports Bootstrap 4 alpha 3

Showing custom message returned from server

ejemplos

As you know, each validator provides the message option to define the error message in case the field doesn't pass the associated validator.

It's recommended to perform the validation on server side after the form passes the client side validation. The usual question is that how to show the messages from the server if the field doesn't pass the validation on server side.

This example will show a handy approach which is described as following steps. To demonstrate the implementation, the example uses a simple registration form that consists of three fields for filling the username, email address and password.

Step 1: Defining the validation rules

In addition to usual validators, we also attach a special validator called blank to each field which need to show the custom message returned from the server.

The blank validator doesn't have any option:

$('#signupForm').formValidation({
    fields: {
        username: {
            validators: {
                notEmpty: {
                    ...
                },
                stringLength: {
                    ...
                },
                regexp: {
                    ...
                },
                // The bank validator doesn't have any option
                blank: {}
            }
        },
        email: {
            validators: {
                notEmpty: {
                    ...
                },
                emailAddress: {
                    ...
                },
                blank: {}
            }
        },
        password: {
            validators: {
                notEmpty: {
                    ...
                },
                blank: {}
            }
        }
    }
});

Since the blank validator always returns true, the field is supposed to pass it whenever the validation is performed in the client side.

We will see how we update the validation result later.

Step 2: Submitting the form data via Ajax

When all fields satisfy the validation rules, we can trigger the success.form.fv event to send the form data to server via an Ajax request:

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

        var $form = $(e.target),                    // The form instance
            fv    = $form.data('formValidation');   // FormValidation instance

        // Send data to back-end
        $.ajax({
            url: '/path/to/your/back-end/',
            data: $form.serialize(),
            dataType: 'json'
        }).success(function(response) {
            // We will display the messages from server if they're available
        });
    });

The error messages returned from server will be processed inside the success handler of the Ajax request. We will see how to do that in the next step.

Take a look at the Using Ajax to submit the form for more details

Step 3: Showing message returned from the server

After getting the data sent from the client via the Ajax request, the server will perform validation using certain programming language. Depend on the validation result, it might response an encoded JSON as

// A sample response if all fields are valid
{
    "result": "ok"
}

or

// A sample response if there's an invalid field.
// It also tell which and the reason why the field is not valid
{
    "result": "error",
    "fields": {
        "username": "The username is not available",
        "password": "You need to have more secure password"
        ...
    }
}

Lastly, we can use the updateMessage() and updateStatus() methods to set the message and validation result of the blank validator:

$.ajax({
    url: '',
    data: $form.serialize(),
    dataType: 'json'
}).success(function(response) {
    // If there is error returned from server
    if (response.result === 'error') {
        for (var field in response.fields) {
            fv
                // Show the custom message
                .updateMessage(field, 'blank', response.fields[field])
                // Set the field as invalid
                .updateStatus(field, 'INVALID', 'blank');
        }
    } else {
        // Do whatever you want here
        // such as showing a modal ...
    }
});

Following is a working example that illustrates all steps above:

For demonstrating purpose, the form randomly displays a custom message for the username field no matter what you put in it
<form id="signupForm" class="form-horizontal" autocomplete="off">
    <div class="form-group">
        <label class="col-xs-3 control-label">Username</label>
        <div class="col-xs-5">
            <input type="text" class="form-control" name="username" />
        </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">Password</label>
        <div class="col-xs-5">
            <input type="password" class="form-control" name="password" />
        </div>
    </div>

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

<script>
$(document).ready(function() {
    $('#signupForm')
        .formValidation({
            framework: 'bootstrap',
            icon: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                username: {
                    validators: {
                        notEmpty: {
                            message: 'The username is required'
                        },
                        stringLength: {
                            min: 6,
                            max: 30,
                            message: 'The username must be more than 6 and less than 30 characters long'
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9_\.]+$/,
                            message: 'The username can only consist of alphabetical, number, dot and underscore'
                        },
                        blank: {}
                    }
                },
                email: {
                    validators: {
                        notEmpty: {
                            message: 'The email address is required'
                        },
                        emailAddress: {
                            message: 'The input is not a valid email address'
                        },
                        blank: {}
                    }
                },
                password: {
                    validators: {
                        notEmpty: {
                            message: 'The password is required'
                        },
                        blank: {}
                    }
                }
            }
        })
        .on('success.form.fv', function(e) {
            e.preventDefault();

            var $form = $(e.target),
                fv    = $form.data('formValidation');

            // For demonstrating purpose, the url is generated randomly
            // to get different response each time
            // In fact, it should be /path/to/your/back-end/
            var url = ['response1.json', 'response2.json'][Math.floor(Math.random() * 2)];

            $.ajax({
                url: url,
                data: $form.serialize(),
                dataType: 'json'
            }).success(function(response) {
                // If there is error returned from server
                if (response.result === 'error') {
                    for (var field in response.fields) {
                        fv
                            // Show the custom message
                            .updateMessage(field, 'blank', response.fields[field])
                            // Set the field as invalid
                            .updateStatus(field, 'INVALID', 'blank');
                    }
                } else {
                    // Do whatever you want here
                    // such as showing a modal ...
                }
            });
        });
});
</script>