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.

Kayla Knight is a web designer and frontend web developer. She specializes in responsive web design, progressive web technologies, and also knows her way around most CMS’s and PHP. You can find out more and check out her portfolio at kaylaknight.co.

Comments

  1. / Reply

    Kayla,

    Love the article. It is a very helpful set of functions that I definitely need on almost every contact/registration form. Thanks for the contribution!

    • Bart,
    • December 21, 2010
    / Reply

    This is going to be so useful in the near future. When I hear form validation, I have the urge to jump out the window. Thanks for the article, Kayla, much appreciated!

  2. / Reply

    Nice and organized looking snippets, I loathe form validation and for some reason I have yet to create a repository of validation code to reuse. Might as well start now.

    Thanks.

  3. / Reply

    Nice post,

    I was building up a similar collection and decided to make this jQuery plugin to do teh job:
    http://www.salesplusplus.com/validatemyform-jquery-plugin-easy-form-validation/

    Thanks

  4. / Reply

    Really a nice article. Up-to now I did all the validation in client side using Jquery. I think it’s really easy and effective.For example if you used the plugin for input validation like phone number you can use masked input plugin http://digitalbush.com/projects/masked-input-plugin/ .It will give you Pone,SSN,Date and tin. From this article I know how to validate in the server side .Thax a lot.

    • Ramesh Vishwakarma,
    • December 21, 2010
    / Reply

    Hey… this is really useful for me… love this :)

    • Mads,
    • December 21, 2010
    / Reply

    This had some good basic tips, but I have to say that I dislike to duplicate validation both on server-side and client-side. I suggest to stick to server-side validation only, and rather use AJAX to show the validation without having to reload the page (emulating client-side validation). This is usually less job for the developers, and it removes a possible security issue: If you have client-side validation, it is usually duplicated on the back-end (ref. this article), and this gives intruders the possibility to go through the code in a white box way; if they break the client-side code (which they can see), then they’ll probably break the server-side code as well.

    I also dislike incomplete regex e-mail validation. One example is GMails incredible useful plus (+) in their e-mail addresses, where you can use “your.name+pagetitle@gmail.com” to filter newsletters etc when you sign up for something. This is a perferctly valid e-mail address, but because many simple filters omit the plus sign as a valid character, this often fail in e-mail validation tests, including the example provided here.

    1. / Reply

      Absolutely agree. I see this all the time in articles like this. Email validation examples that do not contain correct regex to support all valid email addresses. A plus symbol (+) is completely valid in the LHS of an email address, so PLEASE FIX THE ABOVE CODE to include it!

      Invalid code like proposed here continues to propagate the problem further.

  5. / Reply

    Good basic tips here for form validation, but I hardly ever use a Captcha on any of my sites for the simple reason that they can prevent potential leads from completing forms. The amount of times i’ve been stuck on unreadable captchas and had to reload 20x just to submit a form annoys me.

    A simple way to get similar results of captcha is to generate two random numbers between 1~20 and let the user calculate them. (of course no use if they can’t count hehe :p)
    EDIT: hehe i just scrolled down and you have this exact spam prevention measure for your comments.

    I would rather have a small amount of spam than let a potential lead hit the back button and visit a competitor.

      • Kayla,
      • December 22, 2010
      / Reply

      “I would rather have a small amount of spam than let a potential lead hit the back button and visit a competitor.”

      I’m the same way and I agree–I’d rather have a custom made “Captcha” than the image-based captcha service for this reason. I remember having problems with illegible images, etc. myself, and it is annoying, not to mention not very user friendly! For many instances, though, I think the Captcha service or something similar is better than nothing, perhaps not for a comment form, but for a registration or other form that will store more permanent and/or sensitive information.

      It definitely depends on the use of the form, and how a spam-prevention method is implemented. This was a wonderful point to make.

    • Derppy,
    • December 22, 2010
    / Reply

    I just can’t understand why reCAPCHA is so popular and saying that “It’s fine.” is just wrong. It’s horrible for users.

    I think probably the best anti-spam filter is presenting a number of very simple icons and a message like “Select the Clock”. It doesn’t require more than a second of thought from the user and one click. It’s not the most secure thing, but in case someone creates a bot to bypass it (very unlikely), you can just change the icons and add some more.

      • Dan,
      • December 30, 2010
      / Reply

      reCAPTCHA is fine, it tows the line between the captcha being unreadable (a lot of times) and having to implement your own solution. What is so horrible about captcha? Serious web users have had to use it for a long time.

  6. / Reply

    How about using ‘filter_var($email, FILTER_VALIDATE_EMAIL)’ instead of regex for PHP validation?

    • Max Keyner,
    • December 30, 2010
    / Reply

    I personally think it’s better to provide more extensive feedback to the user on input errors.

    Things like little marks to the required fields can help a user to get a better view on his mistakes/blanks.

    That’s why I always write (or reuse) my own jQuery-based validation.

  7. / Reply

    Good!

Leave a Reply

Your email address will not be published. Required fields are marked *

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.