MODX Tutorial: Formit with jQuery Validation

This tutorial was written for MODX Revolution using FormIt and jQuery.
If you don't have FormIt installed yet please visit: FormIt - MODx Documentation
The "official" example of how to setup a simple form with FormIt: Simple Contact Page
Don't forget to download the latest version of jQuery. As of writing it is at version 1.7
Okay, let's get started. First we need to add our FormIt call:
[[!FormIt? &hooks=`email,redirect` &emailTpl=`contactFormTpl` &emailFrom=`from@domain.com` &emailFromName=`Your Site Name` &emailSubject=`Message From Your Site Name` &emailTo=`email@domain.com` &redirectTo=`36` &validate=`name:required, email:email:required, comments:required:stripTags` ]]
contactFormTpl:
<p>Name: [[+name]]</p> <p>Email: [[+email]]</p> <p>Phone: [[+phone]]</p> <p>Budget: [[+budget]]</p> <p>Comments: [[+comments]]</p>
Now we add our form:
<form id="contactForm" action="[[~[[*id]]]]" method="post">
<fieldset>
<label for="name">Your Name* [[!+fi.error.name]]</label>
<input type="text" name="name" id="name" value="First and last name[[!+fi.name]]" class="required" autofocus />
<label for="email">Your Email* [[!+fi.error.email]]</label>
<input type="email" name="email" id="email" value="example@domain.com[[!+fi.email]]" class="required" />
<label for="phone">Your Phone Number</label>
<input type="tel" name="phone" id="phone" value="555-555-5555" />
<label for="budget">Project Budget</label>
<input type="text" name="budget" id="budget" value="Ex. $5000 - $10k" />
</fieldset>
<fieldset class="comment">
<label for="comments">Questions or Comments* [[!+fi.error.comments]]</label>
<textarea id="comments" name="comments" class="required" cols="" rows="">[[!+fi.comments]]</textarea>
<button type="submit" id="submitBtn">Send</button>
</fieldset>
</form>
In this example we're validating two inputs and a textarea: Name, Email and Comments.
The elements that are required need to have class="required"
Ex: <textarea id="comments"... class="required">[[!+fi.comments]]</textarea>
Let's add some jQuery.
We have to catch the form on submit to make sure our required fields have a value.
$(document).ready(function(){
$("form#contactForm").submit(function() {
//When the form is submitted
});
});
Now that we have control of the form, we can add our validation.
$(document).ready(function(){
$("form#contactForm").submit(function() {
//When the form is submitted
var elem = $("form#contactForm").children('fieldset').children('input, textarea');
var error,foc;
//Loop through each input and textarea
elem.each(function(index){
//Does this have the class "required"?
if($(this).hasClass('required')==true){
//It has the class, is it empty or still have the default value?
if(!this.value || this.value == this.defaultValue ) {
//Add the error class for CSS styling
$(this).addClass("error");
//Switch the error var to true
error = true;
//If this is the first required element not filled out, save the ID
if(!foc)foc = $(this).attr("id");
}else{
//If this is filled out make sure it doesn't have the error class
$(this).removeClass("error");
}
}
});
//If error has been switched to true
if (error){
//Focus on the first required element that hasn't been filled out.
if(foc)$('#'+foc).css("color","#000").css("fontStyle","normal").focus();
//Stop the form from submitting
return false;
}else{
//Clear default values on non required elements before submit continues
if(elem.value == this.defaultValue)
this.value = "";
}
});
});
Okay, let's break this down.
First we select our elements using the variable "elem":
var elem = $("form#contactForm").children('fieldset').children('input, textarea');
Then we loop through each of the elements:
elem.each(function(index){
If it has the class "required", check if it is empty or has the default value:
if($(this).hasClass('required')==true){
if(!this.value || this.value == this.defaultValue ) {
If it doesn't meet the requirements, set "error" to true and save the ID:
//Add the error class for CSS styling
$(this).addClass("error");
error = true;
if(!foc)foc = $(this).attr("id"); //If "foc" (focus) is empty set it with the first element's ID that doesn't meet the requirement.
If error is set to true, focus on the first required element and return false (cancel submit):
if (error){
if(foc)$('#'+foc).css("color","#000").css("fontStyle","normal").focus();
return false;
If all the required fields are filled out, clear the non-required fields with the default value and let the form submit:
else{
//Clear default values on non required elements before submit continues
if(elem.value == this.defaultValue)
this.value = "";
Validate The Email Address
We have made sure that all the required fields have been filled in, now we need to make sure the user typed their email address correctly.
function isEmail(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};
The above regular expression checks the format of the address and returns true if it is valid.
var email = $("input#email");
//If email is filled in and the function isEmail returns true
if(email && !isEmail(email.val())) {
email.focus();
email.prev("label").html("Please Enter A Valid Email Address");
error = true;
}else{
email.prev("label").html("Your Email*");
}
If the email is invalid the label will be replaced with our error message, if the address is good the message will remain the same.
Now let's put it all together.
validate-form.js
function isEmail(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};
$(document).ready(function(){
$("form#contactForm").submit(function() {
//When the form is submitted
var email = $("input#email");
var elem = $("form#contactForm").children('fieldset').children('input, textarea');
var error,foc;
//If email is filled in and the function isEmail returns true
if(email && !isEmail(email.val())){
email.focus();
email.prev("label").html("Please Enter A Valid Email Address");
error = true;
}else{
email.prev("label").html("Your Email*");
}
//Loop through each input and textarea
elem.each(function(index){
//Does this have the class "required"?
if($(this).hasClass('required')==true){
//It has the class, is it empty or still have the default value?
if(!this.value || this.value == this.defaultValue ) {
//Add the error class for CSS styling
$(this).addClass("error");
//Switch the error var to true
error = true;
//If this is the first required element not filled out, save the ID
if(!foc)foc = $(this).attr("id");
}else{
//If this is filled out make sure it doesn't have the error class
$(this).removeClass("error");
}
}
});
//If error has been switched to true
if (error){
//Focus on the first required element that hasn't been filled out.
if(foc)$('#'+foc).css("color","#000").css("fontStyle","normal").focus();
//Stop the form from submitting
return false;
}else{
//Clear default values on non required elements before submit continues
if(elem.value == this.defaultValue)
this.value = "";
}
});
//Remove Default Text On Focus
$("input, textarea").focus(function() {
if( this.value == this.defaultValue ) {
this.value = "";
$(this).css("color","#000").css("fontStyle","normal");
}
}).blur(function() {
if( !this.value.length ) {
$(this).css("color","#999").css("fontStyle","italic");
this.value = this.defaultValue;
}
});
});
Chunk: contactFormTpl:
<p>Name: [[+name]]</p> <p>Email: [[+email]]</p> <p>Phone: [[+phone]]</p> <p>Budget: [[+budget]]</p> <p>Comments: [[+comments]]</p>
Contact Page HTML
[[!FormIt? &hooks=`email,redirect` &emailTpl=`contactFormTpl` &emailFrom=`from@domain.com` &emailFromName=`Your Site Name` &emailSubject=`Message From Your Site Name` &emailTo=`email@domain.com` &redirectTo=`36` &validate=`name:required, email:email:required, comments:required:stripTags` ]]
Looking for a MODX / PHP developer?
Do you have something you need developed in MODX or PHP? Send me a quick message, let's talk. I would love to hear about your project.
Hire Me, A MODX / PHP Developer ยป
ad:
May 19, 2012 at 07:14 AM - Unapproved
asdfa