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>
Validation.add method. (
Validation is a global used to store all form validation rules)
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
and can find a butt load of pre added validators in
Just search for
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();