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.
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:
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:
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.
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
Following is a working example that illustrates all steps above: