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();