This is a very quick way to make sure people fill out all fields of a form. It is easy to bypass and is in no way a replacement for server-side form validation, but it's a quick and easy way to prevent invalid form data from being submited. All of the code below requires you to include the jQuery JavaScript library. click here for more information about jQuery
Method 1
This is a simple method that just lets the user know they need to fill out all fields. You simply add the function call to the form tag like this: onsubmit="return validateForm();"
function validateForm(){ if($("input[value='']").length > 0){ alert("You must fill out all form fields."); return false; } return true; }
Method 2
I've heard some mention that the first method doesn't work under certain circumstances so I provided this second method. It works exactly the same way, but is a little bit more code. Also it is implemented exactly the same way.
function validateForm(){ var blankCount=0; $("input").each(function(){ if($(this).val()=="") blankCount++; }); if(blankCount > 0){ alert("You must fill out all form fields."); return false; } return true; }
Quick easy Email validation
It is also very simple to check for a valid e-mail address. All you have to do is make sure the input field has the class "emailfield" and add this code to the bottom of either of the above validation functions (above the return true;)
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; var demail=$(".emailfield").attr("value"); if(!regex.test(demail)){ alert("You must enter a valid e-mail address"); return false; }
Devon
April 26, 2014 at 10:56 am
Thanks! That’s a nice simple way to do it!