Form Validation Snippets and Quick Tips

Form Validation Snippets and Quick Tips

When designing forms, validation is the most important factor to consider. On top of making sure the back-end is secure from spam and malice attacks, validation can aid tremendously in the user experience as well. With proper validation practices, the user will be sure to enter in valid information quickly and almost effortlessly. That is, after all, the goal of good user interface design and development: don’t make the user think.

Form Validation Snippets and Quick Tips

However, validation can also be a hassle. It can be an annoying extra to do with nearly every project, taking up more time and effort. Especially if you’re not the coding-type, it can be even more frustrating. It can be an easy job too, though, with a useful library of code standing by. In this post we’re going to cover some quick snippets so you can copy and paste the repetitive stuff, as well as mention some best user guidelines.

Required Fields

Some fields just need to be filled out – we don’t need blank forms being submitted. Things like names, email, and main messages are all good examples of required fields, but it of course depends on the purpose of the form.

Required Field

For web consistency, always use an asterisk (*) to indicate a required field, and in red if the background color allows. It can also help to display a message for what the asterisk means, although many web users will know automatically. This is the most consistent and non-intrusive way for indicating what is required and what is not. Also check out Lee Munroe’s thoughts on the subject: * Is this a required field?.

Client-Side (JavaScript)

function required(){
	var first = document.forms["myForm"].elements["firstname"].value;
	var last = document.forms["myForm"].elements["lastname"].value;
	var email = document.forms["myForm"].elements["email"].value;
	var message = document.forms["myForm"].elements["message"].value;
	
	if(first == null || first == "" || last == null || last == ""){
		alert("First and last name fields are required.");
		return false;
	}
	else if(email == null || email == ""){
		alert('An email address is required.');
		return false;
	}
	else if(message == null || message == ""){
		alert('Message feild cannot be left blank.');
		return false;
	}else{return true;}
}

Server-Side (PHP)

function required($firstname, $lastname, $email, $message){
	if(empty($firstname) || empty($lastname)){
		return false;
	}
	elese if(empty($email)){
		return false;
	}
	elese if(empty($message)){
		return false;
	}else{return true;}
}

Matching Fields

The two most common fields that need a match check are password and email fields. It is essential to always double check a password field, because 1) the user cannot read the password as they’re typing it, so that leaves room for error and 2) we’ll want the user to log in later (which they can’t do if they signed up with a wrong password).

Matching Fields

Double checking the email field is debatable, however. It really depends on the necessity of the email within the website. For a registration that will require constant email updates, or a feedback form system that will require a response, it can be in the best interest to double check to make sure the email is correct. However, for other email-sensitive cases, double checking can still be intrusive. Simple things like signing up for a newsletter can usually let the double-check slide, and instead “validate” the email in other ways, like in the form of a confirmation page.

Client-Side (JavaScript)

function passwordmatch(form_id){
	var pass1 = document.forms["form_id"].elements["password"].value;
	var pass2 = document.forms["form_id"].elements["password2"].value;
	if(pass1 != pass2){
		alert('Passwords do not match!');
		return false;
	}
}

Server-Side (PHP)

functin passwordmatch($password1, $password2){
	if($password1 != $password2){
		return false;
	}else{return true;}
}

Correct Email Format

A correct email format will include an @ sign, a period (.), and allow only certain characters. Furthermore, these characters will have to be in a correct order. Below are a few snippets, both client-side and server-side anyone can use for email validation.

Email
Image credit: biscotte

Client-Side (JavaScript)

function validate(form_id,email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])
	+\.([A-Za-z]{2,4})$/;
   var address = document.forms["form_id"].elements["email"].value;
   if(reg.test(address) == false) {
      alert("Invalid Email Address");
      return false;
   }
}

Server-Side (PHP)

function isValidEmail($email){
	return preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]
	+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i', $email);
}

Correct Phone Number Format (U.S.)

Regular Expressions can also be easily used to verify a correct phone number. The snippets below are for a common U.S. based phone number, and would have to be altered for other types of patterns.

Phone
Image credit: darwinbell

Client-Side (JavaScript)

function validate(form_id,phone) {
   var reg = /\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x;
   var phone = document.forms["form_id"].elements["phone"].value;
   if(reg.test(phone) == false) {
      alert('Invalid Phone Number: XXX-XXX-XXXX');
      return false;
   }
}

Server-Side (PHP)

function validatePhone($phoneNo){
	return preg_match('/\(?\d{3}\)?[-\s.]?\d{3}
		[-\s.]\d{4}/x', $phoneNo);
}

Correct Zip Code Format (U.S. & Canada)

The following code snippets are for zip code validation in the U.S. and Canada only, but it is likely that these formats would be the most common anyway. If needing a different format for an alternate country, a similar pattern can be used for other types of zip codes or postal address numbers.

Zip Code
Image credit: jamison

Client-Side (JavaScript)

function isValidPostalCode(postalCode, countryCode) {
    switch (countryCode) {
	case "US":
	  postalCodeRegex = /^([0-9]{5})(?:[-\s]*([0-9]{4}))?$/;
	  break;
	case "CA":
	  postalCodeRegex = /^([A-Z][0-9][A-Z])\s*([0-9][A-Z][0-9])$/;
	  break;
	default:
	  postalCodeRegex = /^(?:[A-Z0-9]+([- ]?[A-Z0-9]+)*)?$/;
    }
    return postalCodeRegex.test(postalCode);
}

Server-Side (PHP)

function validateZipCode($postalCode, $countryCode){
	switch ($countryCode){
	case "US":
	  $countryformat = "/^([0-9]{5})(?:[-\s]*([0-9]{4}))?$/";
	  break;
	case "CA":
	  $countryformat = "/^([A-Z][0-9][A-Z])\s*([0-9][A-Z][0-9])$/";
	  break;
	default:
	  $countryformat = "/^(?:[A-Z0-9]+([- ]?[A-Z0-9]+)*)?$/";
	}

	return preg_match('$countryformat', $postalCode);
}

Something’s Actually Selected/Chosen

Sometimes you need to require something that already has a default value. For this we can’t just check to see if it’s empty, because it can never be empty.

Select One
Image credit: joepemberton

An example of this is below, where the user has options in a drop down list, and the default selected value is “Select One.” Of course, we don’t want the user to choose “Select One” because that will give us no valuable information. Similar situations may also be used with radio buttons or pre-defined input fields.


Validation would not be required if there were no “Select One” option in the first place, but in order to make sure the user actively selected something instead of overlooked this portion of a form, we should create this “empty” option.

Client-Side (JavaScript)

function required(){
	var graphicsProgram = document.forms["myForm"].elements["graphicsProgram"].value;
	
	if(graphicsProgram == "Select One"){
		alert("Please choose a graphics program.");
		return false;
	}else{return true;}
}

Server-Side (PHP)

function required($graphicsProgram){
	if($graphicsProgram == "Select One"){
		return false;
	}
	}else{return true;}
}

Within Range

Another common form of validation that is snippet-worthy is checking if a number, or date, is within a certain range. A good example of this would be a birth year, where someone cannot be under a certain age, or could not possibly be older than a certain age. Other uses of this may include budget estimates, distance calculators, or other pieces of data where one would like to take in an exact number, but keep it within limits.





Another way of working with dates and ranges is to actually use a Date object (both in JavaScript, PHP, and other programming languages.) This would actually be a more correct way of doing things, especially if the exact day and month were also important in the range decision. However, to make this solution more versatile, we’ve compiled the code below. A similar technique can then be applied to more customized solutions.

Client-Side (JavaScript)

function withinrange(){
	var currentYear = 2010;
	var birthYear = document.forms["myForm"].elements["year"].value;
			
	var tooOld = currentYear - 100;
	var tooYoung = currentYear - 13;
			
	if(tooYoung < birthYear){
	alert("You must be 13 years or older.");
		return false;
	}else if(tooOld > birthYear){
		alert("You can't possibly be that old!");
		return false;
	}
	else{return true;}
}

Server-Side (PHP)

function withinrange($birthYear){
	$currentYear = 2010;
			
	$tooOld = $currentYear - 100;
	$tooYoung = $currentYear - 13;
			
	if($tooYoung < $birthYear){
		return false;
	}else if($tooOld > $birthYear){
		return false;
	}
	else{return true;}
}

Captcha

Finally, when all is said and done and the form’s been filled out, you’d at least like to make sure that the one entering data into the form is human. To avoid spam bots and malice attacks, always include a captcha before submitting. This can easily be done on the client side and only takes an extra second.

reCaptcha

Some developers choose to create their own captcha through a series of images, simple questions (What color is an apple?), or simple arithmetic. Using a pre-made captcha service like reCAPTCHA is fine too though.

Conclusion

Form validation doesn’t have to be hard, or time-consuming. In many instances, form validation takes the same code over and over again, between form to form, and website to website. There’s really not a lot of variety, so in order to save time and effort, snippets can be of great use. Feel free to take the sample snippets above, customize as necessary, and of course, take out those annoying alerts in the JavaScript and replace with something more user-friendly (Use them for testing purposes). It can be a handy tool to keep these along with other code snippets for quick reference, and perhaps along with form markup templates as well.

These are just among the many types of possible validation, and in a sense, they are the most general as well. Please share snippets or best practices you’ve experienced when working with forms, whether they concern instances that are very specific or perhaps just alternatives to the general snippets above.

Deals

Iconfinder Coupon Code and Review

Iconfinder offers over 1.5 million beautiful icons for creative professionals to use in websites, apps, and printed publications. Whatever your project, you’re sure to find an icon or icon…

WP Engine Coupon

Considered by many to be the best managed hosting for WordPress out there, WP Engine offers superior technology and customer support in order to keep your WordPress sites secure…

InMotion Hosting Coupon Code

InMotion Hosting has been a top rated CNET hosting company for over 14 years so you know you’ll be getting good service and won’t be risking your hosting company…

SiteGround Coupon: 60% OFF

SiteGround offers a number of hosting solutions and services for including shared hosting, cloud hosting, dedicated servers, reseller hosting, enterprise hosting, and WordPress and Joomla specific hosting.