jQuery Required Form Validation
Recently I was asked to create a web form for my internship that had about 30 text input fields. All fields were required, and they asked that form have a validation check. So, instead of writing 30 individual checks for each input, I wrote a some jQuery.
First of all, your required form text inputs must look like this:
<input type="text" title="Input Title" class="required" />
Notice how the required text inputs have the class “required”. Here is the form validation function that gets called when the form tries to submit:
function validate() {
// Initialize empty string for errors
var errors = "";
// Trim whitespace before and after every input
$('input:text').each(function(){
$(this).val($(this).val().trim());
});
// Check if all required inputs are empty
$('.required').each(function(){
if($(this).val() == "") {
errors += "<li>" + $(this).attr("title") + " cannot be blank</li>";
}
});
// If there are no errors, submit the form, otherwise display errors.
if(errors == "") {
return true;
} else {
$('#errors').html("The following errors occured: <ul>" + errors + "</ul>").slideDown();
return false;
}
}
Which uses this prototype function for Strings I call trim. It trims the whitespace from the beginning and end of any String.
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,"");
}
The first line initializes an errors String to hold any errors that may occur
The next function takes the value of each input (of type text), trims the whitespace from it, and then replaces it with the trimmed version. This stops the user from simply entering a few spaces in an input to circumvent required fields.
The next function selects all fields with the class “required”, then for each input, it checks if its value is empty. If it is, it grabs the title of that input and uses it in the error message.
Finally, if there are no errors, the function returns true and the form is submitted. Otherwise, the errors are displayed and the form is not submitted.
This nifty little function not only saved me a ton of time, but also a lot of lines of tedious coding. I hope this helps save you some time too!
