Last week i wrote 25 form validation for PHP. I find useful to have more layer of defend as JavaScript might malfunction or disable and cause your validation to fail but the form is still being passed on to our server. Nonetheless, JavaScript validation does provide certain level of restriction and protection for any web application. Especially when web is evolving quickly in this period of time. We are required to validate any data from our user to prevent any harm that can cause damage to our application and businesses. These JavaScript form validation snippets are needed in every form validation and repeating searching for them is unnecessary and slow down development processes. Therefore, you might want to bookmark these snippets for your future needs
Email Validation
Email validation is the most basic validation that any web application would have.
function isEmail(elem, helperMsg){ var regexp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if(regexp.test(elem.value)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } }
In order to use this, we pass in an object and an alert value if it fail.
var email = document.getElementById('ham_email'); if(isEmail(email, "Invalid Email Format")){ //proceed.. }
URL Validation
URL validation helps to validate whether a particular string is a valid url format.
function isUrl(elem, helperMsg) { var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ if(regexp.test(elem.value.toLowerCase())){ return true; }else{ alert(helperMsg); elem.focus(); return false; } }
In order to use this, we pass in an object and an alert value if it fail.
var link = document.getElementById('ham_link'); if(isUrl(link, "Invalid link")){ //proceed.. }
Username Validation
This function help us validate whether a username contain valid character and length. It accept any underscore, alphabets and numbers within 5-25 characters.
function isValidUsername(elem, msg) { var regx = /^[A-Za-z0-9_]{5,25}$/; if(regx.test(elem.value)){ return true; }else { alert(helperMsg); elem.focus(); return false; } }
You can add additional symbols or change the length of the validation easily by alter the regular expression.
In order to use this, we pass in an object and an alert value if it fail.
var username = document.getElementById('username'); if(isValidUsername(username, "Invalid character found on username!")){ //proceed... }
Password Validation
Here is a simple password strength validation that check the following criteria.
- Passwords will contain at least 1 upper case letter
- Passwords will contain at least 1 lower case letter
- Passwords will contain at least 1 number or special character
- Passwords will contain at least 8 characters in length
- Password maximum length should not be arbitrarily limited
function isStrongPassword(elem, msg) { var regx = /(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/; if(regx.test(elem.value)){ return true; }else { alert(helperMsg); elem.focus(); return false; } }
In order to use this, we pass in an object and an alert value if it fail.
var password = document.getElementById('password'); if(isStrongPassword(password, "Your password fail the basic strength test. \n1. Passwords will contain at least 1 upper case letter\n2. Passwords will contain at least 1 lower case letter\n3. Passwords will contain at least 1 number or special character\n4. Passwords will contain at least 8 characters in length\n5. Password maximum length should not be arbitrarily limited\n")){ //proceed.. }
Numeric Validation
This validate whether a given string contain a valid numeric value which include both negative value and decimal ones.
function isNumeric(elem, helperMsg){ var numericExpression = /^[-]?\d*\.?\d*$/; if(elem.value.toString().match(numericExpression)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } }
In order to use this, we pass in an object and an alert value if it fail.
var price = document.getElementById('price'); if(isNumeric(price, "Invalid value found")){ //proceed... }
Text Empty Validation
In every form validation, there is always a need to check whether a particular text box is empty.
function isEmpty(elem, helperMsg){ if(elem.value.toString().length > 0){ return true; }else{ alert(helperMsg); elem.focus(); return false; } }
In order to use this, we pass in an object and an alert value if it fail.
var name = document.getElementById('ham_company'); if(!isEmpty(name, "Please give us your name")){ //proceed... }
Radio Box Validation
We can determine whether a radio box has been selected using this function.
function hasSelected(elem, msg){ for (i = 0; i < elem.length; i++) //for all check boxes { if (elem[i].checked == true ) //otherwise elements also looks at radio buttons { return true; } } alert(helperMsg); elem[0].focus(); return false; }
Drop Down Validation
We also check whether a particular drop down box has its value selected with the following function.
In order to use this, we pass in an object and an alert value if it fail.
var radio = document.getElementById('radio'); if(hasSelected(radio, Please select your gender")){ //proceed... }
function isSelected(elem, helperMsg){ if(elem.options[elem.selectedIndex].value.toString().length > 0){ return true; }else{ alert(helperMsg); elem.focus(); return false; } }
In order to use this, we pass in an object and an alert value if it fail.
var month = document.getElementById('ham_month'); if(isSelected(month, "Please select a month")){ //proceed... }
Check Box Validation
We can perform check box validation to see whether a particular check box has been selected through this function.
function hasChecked(elem, msg){ for (i = 0; i < elem.length; i++) //for all check boxes { if (elem[i].checked == true ) //otherwise elements also looks at radio buttons { return true; } } alert(helperMsg); elem[0].focus(); return false; }
In order to use this, we pass in an object and an alert value if it fail.
var checkbox= document. getElementsByName('checkbox'); if(checkPhone(checkbox, "Please tick one of the check box")){ //proceed... }
Phone Validation
This function will validate the following criteria phone number.
- phone:
339-4248
339-42-48
339 42 48
339 4248
3394248
(095) #phone#
(095)#phone#
+7 (095) #phone#
+7 (095)#phone#
+7(095) #phone#
+7(095)#phone#
function checkPhone(elem, msg) { var str = elem.value; var phone2 = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/; if (str.match(phone2)) { return true; } else { alert(helperMsg); elem.focus(); return false; } }
In order to use this, we pass in an object and an alert value if it fail.
var phonenumber = document.getElementById('phonenumber'); if(checkPhone(phonenumber, "Invalid Phone Number")){ //proceed... }
File Extension Validation
This function validate whether a particular upload string contains a valid extension.
function isAllowedFileExtension(elem, helperMsg){ var alphaExp = /.*\.(gif)|(jpeg)|(jpg)|(png)$/; if(elem.value != "") { if(elem.value.toLowerCase().match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } else return true; return false; }
In order to use this, we pass in an object and an alert value if it fail.
var upload = document.getElementById('ham_upload'); if(isAllowedFileExtension(upload, "Please Upload Gif, Png or Jpg Images Files Only")){ //proceed... }
IP Validation
Sometimes there is a need to validate whether a particular IP address is valid using JavaScript.
function isValidIPAddress(elem, msg) { var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; ipaddr = elem.value.toLowerCase(); if (re.test(ipaddr)) { var parts = ipaddr.split("."); if (parseInt(parseFloat(parts[0])) == 0) { return false; } for (var i=0; i<parts.length; i++) { if (parseInt(parseFloat(parts[i])) > 255) { return false; } } return true; } else { alert(helperMsg); elem.focus(); return false; } }
In order to use this, we pass in an object and an alert value if it fail.
var ip= document.getElementById('ip'); if(isValidIPAddress(ip, "Invalid IP Address")){ //proceed... }
US Social Security Number Validation
Testing US Social security number can be done with the below function.
function isValidSSN(elem, msg) { var value = elem.value.toLowerCase(); var tmp = false; var re = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/; if (!re.test(value)) { tmp = true; } var temp = value; if (value.indexOf("-") != -1) { temp = (value.split("-")).join(""); } if (value.indexOf(" ") != -1) { temp = (value.split(" ")).join(""); } if (temp.substring(0, 3) == "000") { tmp = true; } if (temp.substring(3, 5) == "00") { tmp = true; } if (temp.substring(5, 9) == "0000") { tmp = true; } if(tmp){ alert(helperMsg); elem.focus(); return false; }else return true; }
In order to use this, we pass in an object and an alert value if it fail.
var ssn = document.getElementById('ssn'); if(isValidSSN(ssn, "Invalid US Social Security Number")){ //proceed... }
US Zip Code Validation
We can valid US zip code using the following function.
function isValidZipCode(elem, msg) { var re = /^\d{5}([\-]\d{4})?$/; var value = elem.value.toLowerCase(); if(re.test(value)){ return true; }else { alert(helperMsg); elem.focus(); return false; } }
In order to use this, we pass in an object and an alert value if it fail.
var zip= document.getElementById('zip'); if(isValidSSN(zip, "Invalid US Zip Code")){ //proceed... }
Date Validation
This function validate date with a given format.
function isValidDate(dateStr, format) { if (format == null) { format = "MDY"; } format = format.toUpperCase(); if (format.length != 3) { format = "MDY"; } if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) || _ (format.indexOf("Y") == -1) ) { format = "MDY"; } if (format.substring(0, 1) == "Y") { // If the year is first var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/ var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/ } else if (format.substring(1, 2) == "Y") { // If the year is second var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/ var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/ } else { // The year must be third var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/ var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/ } // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail if ( (reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) { return false; } var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was // Check to see if the 3 parts end up making a valid date if (format.substring(0, 1) == "M") { var mm = parts[0]; } else _ if (format.substring(1, 2) == "M") { var mm = parts[1]; } else { var mm = parts[2]; } if (format.substring(0, 1) == "D") { var dd = parts[0]; } else _ if (format.substring(1, 2) == "D") { var dd = parts[1]; } else { var dd = parts[2]; } if (format.substring(0, 1) == "Y") { var yy = parts[0]; } else _ if (format.substring(1, 2) == "Y") { var yy = parts[1]; } else { var yy = parts[2]; } if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); } if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); } var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0); if (parseFloat(dd) != dt.getDate()) { return false; } if (parseFloat(mm)-1 != dt.getMonth()) { return false; } return true; }
You will use the function this way,
if (!isValidDate(myDateString, "DMY")) { alert("The date is not in the correct format."); }
Time Validation
This function validate time such as
- 02:25AM
- 00:23PM
- 23:45PM
- 11:23
- etc.
function isValidTime(value) { var hasMeridian = false; var re = /^\d{1,2}[:]\d{2}([:]\d{2})?( [aApP][mM]?)?$/; if (!re.test(value)) { return false; } if (value.toLowerCase().indexOf("p") != -1) { hasMeridian = true; } if (value.toLowerCase().indexOf("a") != -1) { hasMeridian = true; } var values = value.split(":"); if ( (parseFloat(values[0]) < 0) || (parseFloat(values[0]) > 23) ) { return false; } if (hasMeridian) { if ( (parseFloat(values[0]) < 1) || (parseFloat(values[0]) > 12) ) { return false; } } if ( (parseFloat(values[1]) < 0) || (parseFloat(values[1]) > 59) ) { return false; } if (values.length > 2) { if ( (parseFloat(values[2]) < 0) || (parseFloat(values[2]) > 59) ) { return false; } } return true; }
Credit Card Validation
This function validate whether a given string format is similar to a credit card type.
function isValidCreditCard(type, ccnum) { if (type == "Visa") { // Visa: length 16, prefix 4, dashes optional. var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/; } else if (type == "MC") { // Mastercard: length 16, prefix 51-55, dashes optional. var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/; } else if (type == "Disc") { // Discover: length 16, prefix 6011, dashes optional. var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/; } else if (type == "AmEx") { // American Express: length 15, prefix 34 or 37. var re = /^3[4,7]\d{13}$/; } else if (type == "Diners") { // Diners: length 14, prefix 30, 36, or 38. var re = /^3[0,6,8]\d{12}$/; } if (!re.test(ccnum)) return false; // Remove all dashes for the checksum checks to eliminate negative numbers ccnum = ccnum.split("-").join(""); // Checksum ("Mod 10") // Add even digits in even length strings or odd digits in odd length strings. var checksum = 0; for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) { checksum += parseInt(ccnum.charAt(i-1)); } // Analyze odd digits in even length strings or even digits in odd length strings. for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) { var digit = parseInt(ccnum.charAt(i-1)) * 2; if (digit < 10) { checksum += digit; } else { checksum += (digit-9); } } if ((checksum % 10) == 0) return true; else return false; }
Summary
Usually i will use these code in such a way to validate my form. I find it neat and tidy.
form.onsubmit = validation; var validation = function(){ var name = document.getElementById('ham_company'); var email = document.getElementById('ham_email'); var link = document.getElementById('ham_link'); var description = document.getElementById('ham_desc'); var banner = document.getElementById('ham_banner'); var month = document.getElementById('ham_month'); var url = document.getElementById('ham_url'); var upload = document.getElementById('ham_upload'); var quiz = document.getElementById('ham_quiz'); if(isEmail(email, "Invalid Email Format")) if(isUrl(link, "Invalid link")) if(OneNotEmpty(url, upload, "Either image url or upload must be perform!")) if(isAllowedFileExtension(url, "Please provide an image with Gif, Png or Jpg extension Only")) if(isAllowedFileExtension(upload, "Please Upload Gif, Png or Jpg Images Files Only")) if(isSelected(month, "Please select a month")) if(isSelected(banner, "Please select a banner")) if(NotEmpty(quiz, "Please answer the quiz")) if(NotEmpty(name, "Please give us your name")) { return true; } return false; }
On the other hand, you can always brings up new form validation snippets to share with me in this article. I will love to know 🙂
I hate Javascript, but I can see that you didn't check if trim(input) == empty.
Trim doesn't exist in JavaScript, so searching for a solution I crossed with a script that implements this. Here it is:
function trim(c){
for(i=0;i=0;i=c.length-1){
if(c.charAt(i)==" ") c=c.substring(0,i);
else break;
}
if (c=='') return false;
else return true;
}
It's dirty, it can be optimized, minified and obfuscated, but it does his job.
Greetings !!
lol, after checking, the above function is wrong... It should be:
function trim(c){
for(i=0;i=0;i=c.length-1){
if(c.charAt(i) == " ") c=c.substring(0,i);
else break;
}
if(c=='') return false;
else return true;
}
Greetings !!
wtf? It seems WP doesn't like it when you include some JavaScript snippet lol... Please go to unreal4u for complete code xD
@unreal4: that's a lot of comment, haha..
i purposely didn't trim when i validate actually 🙂
The reason is simple. Something that user mistakenly type wrongly shouldn't be corrected by our script especially on the username and password validation since they are the most sensitive part of a system that hacker would like to break. And helping by trimming our value should be avoided. (this should be the same with PHP side)
Nonetheless, you are right on other fields that trim should exist. But i will leave it optional for everyone since we will still have to trim it on the server side scripting as the data still wasn't trimmed when it is passed to server. Hence, i tried to avoid additional code and logic into the JavaScript code 🙂
Steven have a multiple version of trim that i always refer to since there are many participates on his many trim version.
Once again! Thanks for the participation! I learn a lot from you lately 😀
@Clay: I couldn't edit xD Sorry for that.
Nice compilation of trim functions there! I've included my demo in the benchmark script Steven's website and I realized it was really far from perfect.
It scored at third place... from the bottom xD
trim8: 3739ms (length: 27654) --> slowest
trim11: 37ms (length: 27654) --> fastest
trim13: 3051ms (length: 27657) --> mine xD
However, the worst part is that my function wasn't reliable. The string length isn't the same as the others are. That is something to worry about! So if you're reading this, DON'T use my previously posted trim solution!
Anyway, I've learned a lot also! Like I said, I just hate JavaScript, so this article goes directly into my favs! xD
JavaScript is fun! But troublesome sometimes XD
need some help in compiling your comments? haha..
Thanks - I hate constructing regular expressions!
I love Javascript though 🙂