You will recieve your password to this address. Address is not made public.

Your preferred username that is used when logging in.

Combined server and client-side validation


Validator demo 3 / 6 : Combined server and client-side validation

Many times both client and server-side validation is needed. This tool makes it easy and you are not tied to any specific server-side framework.

Sample registration form

Enter bad values and then press the submit button.


Here we spice our minimal setup with some server-side validation. On the server we have defined that name and age fields are never valid.

JavaScript coding

Here is how we do it. We first initialize client-side validation with the validator() call and ad a custom form submission logic after that. You can use isDefaultPrevented() method on the jQuery Event object to test whether client side validation is passed.

// initialize validator and add a custom form submission logic
$("#myform").validator().submit(function(e) {

	var form = $(this);

	// client-side validation OK.
	if (!e.isDefaultPrevented()) {

		// submit with AJAX
		$.getJSON("server-fail.js?" + form.serialize(), function(json) {

			// everything is ok. (server returned true)
			if (json === true)  {
				form.load("success.php");

			// server-side validation failed. use invalidate() to show errors
			} else {
				form.data("validator").invalidate(json);
			}
		});

		// prevent default form submission logic
		e.preventDefault();
	}
});

Here we have used a simple return value true to indicate that the data was valid on the server-side. You can do whatever you wish when the data is good. Here we replaced the form contents with a server-side page. If the data was not valid we use the invalidate method to display errors to the user. The invalidate method accepts an object argument which is a field name to error. The server-fail.js is our server-side "logic" and it always returns the following:

Server-side return value

You need to place the script block after the HTML code or you can alternatively use jQuery's $(document).ready to execute the script as soon as the webpage's Document Object Model (DOM) has been loaded. Read more about that from the User's Manual.


Here is the standalone version of this demo. You can freely study and copy its source code.