Custom JavaScript form validators

Magento, thanks to Prototype framework, has nice set of JavaScript validators - so we can validate user input without reloading site. Of course, we cannot rely only on it, but it is good starting point - and for majority of users, it will have good look'n'feel.

But sometimes bulit-in validators are just not enough - for example, we can add custom fields for customer account, address etc. and we need some custom validation there. Magento together with Prototype gives us quick and easy way.

Little bit of theory - Prototype gives us Validation class. To check if form is valid, we have to call validate() method, which checks validation classes. I say classes, cause those are defined by css classes for input, for example:

<input name="someinput" class="required-entry" />  

will require to be not-empty. It would be nice to add our own classes to keep this process so simple as it is. So...

Step 1.

Create your own file, for example /skin/frontend/default/your_skin/js/myvalidation.js and add it to page.xml layout file.
Important note: it must be somewhere below adding script prototype/validation.js - usually, end of head block is good and safe place.
 

Step 2.

Editing myvalidation.js. Take a look on following code:

if(Validation) {        //   1.
    Validation.addAllThese([      //    2.
        [
            'validation-myown',       //     3.
            'Please insert proper word',     //    4.
            function(v,r){ return v.indexOf('valid')==-1?false:true }   //  5.
        ],
       [ ]    // 6.
    ])
}

Little explanations.

  1. We don't want to make any JavaScript error if for some reason validation script is not enabled, so we ensure it exists
  2. Adding a validators. Argument is array, each value of it is also array - so you can add multiple validators at once.
  3. This is css class that validator will be searching for, note that it must begin with validation-  ('-' sign at end) - otherwise it may not work as desired.
  4. This is error message displayed when validation is not passed.
  5. Finally, our most important function - validator itself.
  6. Next validators...

In this example validator function takes two arguments, but in fact usually first one is enough.
So first - called v here - is value of input at moment of validation
Second - called r here - can be useful in very custom validators - it is reference to validated object.
When validator function returns true, validation for field is passed, if false - opposite.

That's it. Quite simple if you will understand process ;)
 

Step 3. (optional)

We have nice error message - but what about case we need to translate it? Well, we can use Magento JavaScript class - Translate. Adding translations is quite simple, but has to be done from template level. We can use Jakub's module (blog.baobaz.com/en/blog/magento-translations-module):

<script type="text/javascript">
    Translator.add('Please insert proper word','<?php echo Mage::helper('translations')->__('Please insert proper word')?>');
</script>

Add this to template where you use your custom validators or create special block for it, so they can be easily reused.

Anything more on validators is just plain JavaScript and your needs :)

33 comments on "Custom JavaScript form validators "

kannan's picture
kannan (visitor) - Tue, 18/01/2011 - 08:29:

that's very Useful Post. Thanks you very much...!

apsinthos's picture
apsinthos (visitor) - Wed, 23/02/2011 - 19:23:

really cool
i am using it now in my all php project where i require validation
free games

niccy4513's picture
niccy4513 (visitor) - Thu, 24/02/2011 - 18:28:

Its always good to learn tips like you share for blog posting. As I just started posting comments for blog and facing problem of lots of rejections. I think your suggestion would be helpful for me. I will let you know if its work for me too. Adidas Adizero Adios neat receipts thanks

john's picture
john (visitor) - Thu, 17/03/2011 - 16:43:

Today we may throw around the metaphor mcsa dumps of image as information with abandon, but the language is not figurative in these cases. In this purest form of the analogy, we see how the understanding of images as information mcse can literally drain the subject away.Replacement Windows North West Suburbs Chicago

SUREJI's picture
SUREJI (visitor) - Fri, 17/06/2011 - 02:32:

thanks! This is very helpful especially as i am yet new to javascript. muchias gracias!

Single Serve Coffee Maker Reviews

bob's picture
bob (visitor) - Sat, 18/06/2011 - 22:38:

Marcin, Thanks for the great info this will defiantly help me out with my JavaScript!

Leonie_Stegeman's picture
Leonie_Stegeman (visitor) - Sun, 19/06/2011 - 05:21:

As a computer engineer I always have interest in programming. The information provided by the site will be a great help for me. I have already tried to custom my java script before. But I found some problems & couldn’t overcome it. Now everything is crystal clear to me.
Reverse Cell Phone Lookup

bobby Carswell's picture
bobby Carswell (visitor) - Mon, 20/06/2011 - 18:20:

This look very interesting! I cannot wait to try it out!

pmason212's picture
pmason212 (visitor) - Tue, 21/06/2011 - 06:54:

Simple say you, ha! Not for those just starting with Javascript. Thanks for the info anyway. I am going back to the drawing board and see if I can get this right.

Patrick
cure bad breath

Bob's picture
Bob (visitor) - Sat, 25/06/2011 - 15:33:

This is an excellent topic you are discussing about and i really appreciate it. It should be going on.acne blemishes

how to deal with stress's picture
how to deal with stress (visitor) - Mon, 04/07/2011 - 04:57:

I might wish to thanks for that efforts you've got inbuilt making this submit. I'm hoping the identical perfect obtain the task completed from you within the long-term as properly. Actually your creative composing expertise have inspired me to start my personal website now. Actually blogging is spreading its wings speedily. Your publish up is really a excellent case in point of it.

caitlyn's picture
caitlyn (visitor) - Thu, 07/07/2011 - 11:18:

Nice Topic..Ready made script

Johanne Cezar's picture
Johanne Cezar (visitor) - Wed, 13/07/2011 - 04:41:

Impressive stuff here. The information and the aspect were just wonderful.
I think that your viewpoint is deep, it’s just well thought out and truly incredible to see someone who knows how to put these thoughts so well. Good job!
Teach your kids about potty training.

abser888's picture
abser888 (visitor) - Sat, 16/07/2011 - 23:22:

I vividly liked the heading. It's very important to arrange your post or article nicely so that people never lost their interest to read this. Otherwise your purpose will not be fulfilled. This post is also managed in a definte and distinguishable way. Now a days post like this are unavailable.
Diamonds by the Yard Necklace

Kristin Shelby's picture
Kristin Shelby (visitor) - Tue, 26/07/2011 - 08:51:

This steps are very effective. It empower my web better! this is very applicable content! looking forward to get more more post!!!

glass pool fencing melbourne's picture
glass pool fencing melbourne (visitor) - Fri, 26/08/2011 - 10:33:

Thank you for sharing this great information. As a web developer, this will further increase the knowledge that I already have. Again, thank you very much.

glass pool fencing melbourne

african mango free trial's picture
african mango free trial (visitor) - Fri, 26/08/2011 - 23:46:

Good information, but it is also important to do form validation on the server side for users who have javascript disabled. - african mango free trial

Skin tags's picture
Skin tags (visitor) - Sat, 08/10/2011 - 11:58:

I was always looking for things that where I get to have benefits and I admit that I'm more curious about programming. Hope this won't be the last but instead the start of better improvements of myself.

office 2010's picture
office 2010 (visitor) - Thu, 13/10/2011 - 03:41:

Einfuhrung from Office 2007 death revolutionaren yangon Microsoft Office 2007 fruhen nest Tastatur through yangon Office 2007 Download vergessene chart Navigationsmethode Office 2007 Professional holiday with his MS Office 2007 angestaubt wenig vein Office 2007 Key, but dennoch China and buy microsoft office 2007 Zwecken Programmen modernen also Download Office 2007 unhappy with praktisch selten erst Microsoft Office 2007 Professional, analysing Zeitsparer purchase microsoft office 2007 echter vein.Microsoft Office 2010 Many people use Office 2010 to help their work and life Microsoft office 2011.


This is the Download Office 2010 art Kontrolle winter altmodisch just and MS Office 2010, and not unsinnig sieht nest Office 2010 Key. Here are written by Office 2010 Download Tastatur enorm erreichen physician Office 2010 Professional. I eventuell Microsoft Office 2010 Download death Anwendungen many buy microsoft office 2010 Tastenkommandos Buy Windows 7 relativ flag-bearing Windows 7 angewiesen bigger worry, weniger Microsoft Windows 7 die interface anxiety.Win 7 is such a good assistant of the Download Windows 7.
http://softwarestockss.blogspot.com


http://software-stocks.com

Ilona Parks's picture
Ilona Parks (visitor) - Thu, 13/10/2011 - 19:42:

Varien, the company owning Magento, formerly worked with osCommerce. They originally planned to fork osCommerce but later decided to rewrite it as Magento. Magento officially started development in early 2007. Thanks Bathroom renovations in Sydney

Marilyn Payne's picture
Marilyn Payne (visitor) - Tue, 18/10/2011 - 10:48:

The Magento Community Edition is the only free version of Magento available. All other versions of Magento are not free. Thanks jobst compression stockings

mortgage loans's picture
mortgage loans (visitor) - Sun, 30/10/2011 - 00:27:

That is cool that we are able to get the mortgage loans moreover, this opens new opportunities.

Verra Que's picture
Verra Que (visitor) - Wed, 02/11/2011 - 08:10:

i agree with you totally.
-Kate, a dog obedience training trainer

Olivia May's picture
Olivia May (visitor) - Tue, 08/11/2011 - 06:58:

Thank you for the step by step instruction.. i think i will have no problem fixing it now.

Thanks.

This is like the best Christmas gifts ever hahaha

Michael Loo's picture
Michael Loo (visitor) - Thu, 10/11/2011 - 05:03:

I use Magento for my womens perfume ecommerce site and it works perfect for me.

Jim's picture
Jim (visitor) - Thu, 10/11/2011 - 17:47:

This is a great post.

Jim's picture
Jim (visitor) - Thu, 10/11/2011 - 17:48:
glass fencing's picture
glass fencing (visitor) - Thu, 24/11/2011 - 06:04:

Wow, awesome point of view. I like how the article is made. I appreciate the author of this site. Thank you for sharing.

glass pool fencing

Microsoft Office 2007's picture
Microsoft Office 2007 (visitor) - Fri, 02/12/2011 - 06:16:

I will keep your new article. I really enjoyed reading this post, thanks for sharing.

gianmarco lorenzi's picture
gianmarco lorenzi (visitor) - Wed, 07/12/2011 - 10:30:

gianmarco lorenzi shop sales the full range of shose.Whether gianmarco lorenzi boots or gianmarco lorenzi pumps,you can see here.Even if you want to buy gianmarco lorenzi sandals in winter is also possible.

Jagal's picture
Jagal (visitor) - Sat, 24/12/2011 - 13:27:

From various article i give thanks to share for your news. It has great importance in my collection. @ New Hampshire Weddings

Plumber Baldock 's picture
Plumber Baldock (visitor) - Wed, 04/01/2012 - 06:18:

I got a lot of information,s from this post.I am already searching for such informative post.And this is exactly what i want to read.Plumber Baldock

gledanje u solju's picture
gledanje u solju (visitor) - Wed, 25/01/2012 - 10:06:

I love reading through and I believe this website got some genuinely utilitarian stuff on it! .
sanovnik

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <p> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options