Validating

July 24th, 2008

When dealing with forms its very important to validate what the user entered so you don’t get false email address, phone number, zip code, etc. There are multiple ways to validate what the user entered in the input field of your form(s). The way I suggest and I am going to share with you is through Javascript. I wrote a nifty little function called validate which takes the two required parameters, the first being what you want validate, and the second is the value or string to validate/test it with. Here is the function:

[js]
function validate(what,str) {
if(what == “email”) {
// sample@sample.com
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return filter.test(str);
} else if(what == “phone”) {
// (123) 456-7890
var filter = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;
return filter.test(str);
} else if(what == “num”) {
// must be a number, or can’t be zero
if((str / str) == 1 && str != 0) { return true; }
else { return false; }
} else if(what == “zip”) {
// 12345 or 12345-1234
var filter = /\d{5}(-\d{4})?/;
return filter.test(str);
} else if(what == “date”) {
// MM/DD/YYYY
var filter = /^([1-9]|0[1-9]|1[012])\D([1-9]|0[1-9]|[12][0-9]|3[01])\D(19[0-9][0-9]|20[0-9][0-9])$/;
return filter.test(str);
} else if(what == “url”) {
// http://www.sample.com or www.sample.com
var filter = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
return filter.test(str);
} else if(what == “ext”) {
// personally, I only accept images with jpg/jpeg, gif, or png format. But this can anything to your liking
str = str.toLowerCase();
if(str.lastIndexOf(“.jpg”) == -1 && str.lastIndexOf(“.jpeg”) == -1 && str.lastIndexOf(“.gif”) == -1 && str.lastIndexOf(“.png”) == -1) { return false; }
else { return true; }
}
}
[/js]

This function does a lot different validating and testing, and of course this can continue to grow to your pleasing. As of now, the function is set up to return either true or false. I suggest keeping it this way if you plan adding or changing some of the regular expression checking. This is how to use the function:

[js]
// get the phone value from the form
var phone = document.forms[0].phone.value;

// validate the phone number
if(!validate(“phone”,phone)) {
alert(“Invalid Phone Number entered”);
return;
}
[/js]

If the phone number is invalid, then it will do an alert telling the user that they didn’t enter the correct syntax for the phone number. If it was entered correctly then it was entered correctly and javascript will continue with the rest of the script.

I hope you find this useful. Enjoy!

Javascript > Website

Leave a Reply

Enter code snippets inside of <pre> and </pre>