Showing custom message returned from server

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.

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:

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

Submitting the form data via Ajax

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

Tip

We're using a built in helper method, FormValidation.utils.fetch, to send the data to given back-end. Anyway, you can use whatever method you're familiar with such as Github's fetch implementation.

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

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

or

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

Following is a working example that illustrates all steps above:

Note

For demonstrating purpose, the form randomly displays a custom message for the username field no matter what you put in it

More examples

Related validators

The following validators might be useful to you.