SSbits - Home page
Site by Carbon Crayon
Submit a Post >

Tutorials - Big bits of code to help you do more

Using jQuery for form validation

SSBjqueryvalidation

 Source files (2.5 KB)  Demo (admin/pass)

As you may have noticed, SilverStripes built in form validation is based on Prototype and is pretty limited. It also means that even though you might be using jQuery for other things on your site, you will still need to load prototype.js and all the associated files that SilverStripe requires for it's built in JavaScript form validation.

Note. This tutorial continues from the Creating a Simple Contact Form tutorial, if you are not sure about form creation is SilverStripe, read that first.

With this in mind using a jQuery validator, such as the excellent Validate plugin has some obvious benefits:

  1. Validate multiple forms on a single page
  2. Customize error messages
  3. More control over inline error styling
  4. Remove the need for loading extra JS files, such as Prototype.js and Behavior.js etc. (more than 90KB in total)
  5. Extended validation options as well as the ability to create custom regex validation rules.

So now that you are (most likely) convinced about the benefits of using jQuery validation let's get started.

Removing SilverStripe's built in JS Validator

The first thing we need to do is disable SilverStripe's Prototype validation. We can do that with a single line in our ContactPage_Controller's init() function:

 

class ContactPage_Controller extends Page_controller{
   
   function init() {
	parent::init();
		
      	Validator::set_javascript_validation_handler('none'); 		
   }
.
.
.
 
}

 

Now if you try the form you will notice that the live Javascript validation is no longer present and more importantly all of the files associated with form validation in SilverStripe (Prototype.js etc) and the messy inline Javascript at the bottom of the page's source is also no where to be seen. Great!

Including the jQuery Validator files

Now let's go about adding in our sexy jQuery validation. First things first we need to include both the jQuery source file and the jQuery.Validate plugin. You may already be including jQuery in your Page.php init() function for other uses, if so just skip the first include.
Note.
I tend to include jQuery from the google API index as it is often already cached by the users browser, but you can include the one inside the SilverStripe JSparty folder if you prefer. However I could not get the SilverStripe included jquery.validate.min.js to work with the lastest jQuery release, so again I used a hosted version.

So now your init() function will look like this:

function init() {
	parent::init();
		
    Validator::set_javascript_validation_handler('none'); 		
	Requirements::javascript("http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js");
	Requirements::javascript("http://ajax.microsoft.com/ajax/jquery.validate/1.8/jquery.validate.min.js");
 
}

 

Applying the Validation to the form

Now that we have our jQuery files included we can go about validating our form fields. Due to the great design of the plugin, this is extremely easy. For brevity sake, we are going to include this script by adding a customScript requirement to our init() function, but you could just as easily place it in a seperate .js file and include it in the same was as the files above. So now our innit() function looks like this:

function init() {
	parent::init();
		
      	Validator::set_javascript_validation_handler('none'); 		
	Requirements::javascript("http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js");
	Requirements::javascript("http://ajax.microsoft.com/ajax/jquery.validate/1.8/jquery.validate.min.js");
		
	Requirements::customScript('
		jQuery(document).ready(function() {
			jQuery("#Form_ContactForm").validate({
				rules: {
					Name: "required",
					Email: {
						required: true,
						email: true
					},
					Comments: {
						required: true,
						minlength: 20
					}
				},
				messages: {
					Name: "I would really love to know your name",
					Email: "It is quite important that you give me your actual email address so I can send you messages",
					Comments: "What are you thinking? Tell me"
				}
			});
		});
	');
		
}

 

Although this may look a little scary, it's really very simple. We are simply calling the jQuery.validate() function on #Form_ContactForm which is the id of the <form> tag. We then define the rules by passing in a series of options for each field, following the same field names as defined when creating the fields. For Name we simply tell the validator that it is required, while for Email we tell it that it's required and is of type 'Email'. For the Comments field we also specify a minimum length to make sure people write something of significance.

We then define some suitably creepy error messages that will be displayed if validation fails.

Done! You now have a jQuery Validated form. Best of all the server side SilverStripe validation still works, so you have something to fall back on if Javascript is switched off.

Styling the error messages

As with the rest of the plugin, styling errors is super simple. Here are a couple of css rules to get you going:

label.error{
	border: 1px solid #aaa;
	background: #aa2222;
	color: #fff;
	padding: 5px;
	margin: 0;
	width: 100%;
}
input.error{
	border: 1px solid  #aa2222;
}

 

Using multiple forms on a single page

This validation will work on as many forms as you like per page, but in order for it to work you need to call the jQuery.Validate() function and pass it's options for each form. So copy everything inside the jQuery(document).ready(function(){ and change the id that is passed into the validate() function.

Aram Balakjian avatar

Aram Balakjian

Aram is a web developer running London based agency Aab Web. He has a strong passion for developing attractive, usable sites around the SilverStripe CMS.

  • Colin Burns
    05/04/2011 9:01am (4 years ago)

    Thanks for the tutorial, really helpful and super easy to implement.

    I am using memberprofiles module and ran into 2 problems. The first one I have solved. Using the code you have above did not stop prototype etc from loading, although it did on other forms. With the memberprofiles module I had to add the following:

    public function init() {
    parent::init();
    Validator::set_javascript_validation_handler('none');
    Requirements::block('sapphire/thirdparty/prototype/prototype.js');
    Requirements::block('sapphire/thirdparty/behaviour/behaviour.js');
    Requirements::block('sapphire/javascript/prototype_improvements.js');
    Requirements::block('sapphire/javascript/Validator.js');
    Requirements::block('sapphire/javascript/i18n.js');
    Requirements::block('sapphire/javascript/lang/en_US.js');
    Requirements::javascript("http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js");
    Requirements::javascript("mysite/javascript/jquery.validations.rules.js");
    Requirements::customScript('
    // VALIDATION CODE GOES HERE
    ');
    }

    As you can see I have had to explicitly block the prototype files etc. Hopefully this helps someone else save an hour ;)

    Second problem is that the Password and Confirm Password fields in SilverStripe output the field names like Password[_Password] or Password[_Confirm_Password].

    When I add these field names into the rule it breaks the JS and doesn't work. Any suggestions?

    Cheers,
    Colin

  • eceer
    20/04/2011 1:27am (4 years ago)

    @Colin Burns thank you very much you just saved me a fair swag of time. Thanks again.

  • salva
    21/04/2011 4:06pm (4 years ago)

    Hey Aram,

    is is correct that the the included jquery files and the custonScript will be embeded just before the closing BODY tag?

    salva

  • Aram Balakjian
    21/04/2011 4:07pm (4 years ago)

    Hi Salva,

    yes this is convention as it prevents the page being help up by loading JS.

    Aram

  • gav
    22/04/2011 1:05pm (4 years ago)

    If your using the blog module, there is a couple more js scripts you should block:

    Requirements::block('cms/javascript/PageCommentInterface.js');
    Requirements::block('sapphire/thirdparty/scriptaculous/effects.js');

  • Nobrainer Web
    13/01/2012 9:04pm (3 years ago)

    Hi Aram,

    I just want to thank you for this lovely SilverStripe resource site - needed a simple contact form in SilverStripe, and wanted to use spam protection and jQuery validation, found all i needed in this post and the Creating a simple contact form post :-)
    All working in a matter of minutes thx to you.

    Keep up your great work!

  • Brad Jeffery
    10/05/2012 2:23am (2 years ago)

    I had the same issue, but mine was a nice weird one. On our page.ss, at the very bottom we had the following code just before the </body>:

    <!--uncomment if eventsearch -->
    <!--<script src="themes/[...]/js/eventsearch.js"></script> -->

    I followed the instructions on this page to a tee, but alas no validation still. So I looked at the source code and found that the validation code inside the init() was being inserted INSIDE these comments tags!

    I removed the tags as we really don't need them and voila! I think this might be a bug in SS... anyways hope this may help someone else as it took me hours to figure out why validation wasn't working...

  • James Pluck
    14/06/2012 10:31am (2 years ago)

    Excellent tutorial. Helped me greatly when I was trying to make a site's contact form have a more polished and professional look.

    Thanks once again, Aram!

Post a comment ...

You cannot post comments until you have logged in. Login Here.

Advertisement

Site of the Month

Find SSbits on

Top Contributers

Rank Avatar Name
1 article image Aram Balakjian
2 article image Daniel Hensby
3 article image Marcus Dalgren
4 article image Hamish Campbell
5 article image Ty Barho
6 article image Martijn van Nieuwenhoven
7 article image Darren-Lee
8 article image Roman Schmid
9 article image Matt Clegg
10 article image dalesaurus

View full leaderboard


Advertisement