edselweb

Creating a sign-up form with validation using jQuery

In JavaScript, jQuery on November 9, 2009 at 10:50 am

Objective:

To create a sign-up form with validation using jQuery.

Skill Set:

jQuery, HTML, CSS

Demo:

Sign-Up Form with validation using jQuery

Steps:

  • Download jQuery library here.
  • Download jQuery Form Validation plugin here.
  • Insert this code within the header tag:
  • <script src=”jquery-1.3.2.min.js” type=”text/javascript”></script>
    <script src=”jquery.validate.pack.js” type=”text/javascript”></script>
  • Insert the following code within the header for the plugin:
$().ready(function() {
	// validate signup form on keyup and submit
	$("#signupForm").validate({
		rules: {
			firstname: "required",
			lastname: "required",
			username: {
				required: true,
				minlength: 2
			},
			password: {
				required: true,
				minlength: 5
			},
			confirm_password: {
				required: true,
				minlength: 5,
				equalTo: "#password"
			},
			email: {
				required: true,
				email: true
			},
			topic: {
				required: "#newsletter:checked",
				minlength: 2
			},
			agree: "required"
		},
		messages: {
			firstname: "Please enter your firstname",
			lastname: "Please enter your lastname",
			username: {
				required: "Please enter a username",
				minlength: "Your username must consist of at least 2 characters"
			},
			password: {
				required: "Please provide a password",
				minlength: "Your password must be at least 5 characters long"
			},
			confirm_password: {
				required: "Please provide a password",
				minlength: "Your password must be at least 5 characters long",
				equalTo: "Please enter the same password as above"
			},
			email: "Please enter a valid email address",
			agree: "Please accept our policy"
		}
	});

	// propose username by combining first- and lastname
	$("#username").focus(function() {
		var firstname = $("#firstname").val();
		var lastname = $("#lastname").val();
		if(firstname && lastname && !this.value) {
			this.value = firstname + "." + lastname;
		}
	});

	// check if confirm password is still valid after password changed
	$("#password").blur(function() {
		$("#confirm_password").valid();
	});

	//code to hide topic selection, "none" class is use to hide topic at first
	var newsletter = $("#newsletter");
	// newsletter topics are optional, hide at first
	var inital = newsletter.is(":checked");
	// [inital ? "removeClass" : "addClass"] ---- if initial is true, then remove class, otherwise add class
	var topics = $("#newsletter_topics")[inital ? "removeClass" : "addClass"]("none");
	var topicInputs = topics.find("input").attr("disabled", !inital);
	// show when newsletter is checked
	newsletter.click(function() {
		topics[this.checked ? "removeClass" : "addClass"]("none");
		topicInputs.attr("disabled", !this.checked);
	});
});