Categories


Archives


Recent Posts


Categories


Magento Custom Form Validation

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

Magento’s form validation seems scary at first, but using it is actually quite easy.

First, create for your form.

<form action="<?php echo $this->getUrl('/some/route/thing');?>" id="theForm">
    <input type="text" name="foo" id="foo" />
</form>

Next, run this bit of javascript to turn your plain old form into VarienForm

<script type="text/javascript">
//<![CDATA[
    var theForm = new VarienForm('theForm', true);
//]]>   
</script>

Then, write your validation as a javascript function using the Validation.add method. (Validation is a global used to store all form validation rules)

<script type="text/javascript">
//<![CDATA[
    var theForm = new VarienForm('theForm', true);
    Validation.add('validate-must-be-baz','You failed to enter baz!',function(the_field_value){
        if(the_field_value == 'baz')
        {
            return true;
        }
        return false;
    });

//]]>   
</script>

The first paramater is your validation name. The second paramater is your error message, and the third paramater is an inline javascript function that will be passed the field value as a parameter.

Finally, take you validation name from above (validate-must-be-baz) and add it to your field as a css class

<form action="<?php echo $this->getUrl('/some/route/thing');?>" id="theForm">
    <input type="text" name="foo" id="foo" class="validate-must-be-baz" />
</form>

And that’s it. The object initialized by VarienForm will automatically hook into your onSubmit, and if your field value fails the validation function, the PrototypeJS animated errors will take over.

Two last things. You can have multiple rules

class="validate-cant-be-bar validate-cant-be-bar"

and can find a butt load of pre added validators in

js/prototype/validation.js

Just search for Validation.addAllThese.

Update: One thing that might trip you up, and is a perfect example of Magento at its worst, is this validation has a different implementation in the frontend application vs. the adminhtml application. In the backend you need to say

var theForm = new varienForm('theForm', true);

That is, it’s varienForm with a lowercase v. That’s because each Magento area has its own implementation of the form class

#File: js/varien/form.js
VarienForm = Class.create();

#File: js/mage/adminhtml/form.js
var varienForm = new Class.create();

Copyright © Alana Storm 1975 – 2023 All Rights Reserved

Originally Posted: 16th June 2011

email hidden; JavaScript is required